作者clsmbstu (missing)
看板Python
标题[问题] 同样的xpath却不一定能抓到东西?
时间Wed Apr 11 00:20:23 2018
我正想挑战用Python爬虫,但越爬越发现好像碰到大魔王...
由於是aspx网页,用requests去造访网页不会抓到动态表格的全部内容,
不知道我有没有理解错?
但是我在实作selenium的过程中发现,原本我用requests还能抓到的资料,
到了selenium却抓不到,只剩空list?
import requests
from selenium import webdriver
from time import sleep
from lxml import etree, html
url = "
https://www.ntuh.gov.tw/labmed/检验目录/Lists/2015/BC.aspx"
browser = webdriver.Chrome()
browser.get(url)
# The url is visited with Chrome correctly
root = etree.fromstring(browser.page_source, etree.HTMLParser())
root.xpath("//table[@class='ms-listviewtable']/tr")
# It gives me [] while browser.page_source is a string of html
到这里就可以发现这个xpath没抓到东西。
但是,实际上这个xpath在我用requests抓时是有用的:
result = ""
while result == "":
try:
# Certificate is not verified to bypass the SSLError
# Not secure though
result = requests.get(url, verify = False)
break
except:
sleep(5)
continue
# Transform it into an element tree
root = etree.fromstring(result.content, etree.HTMLParser())
# Parse the information with Xpath
root.xpath("//table[@class='ms-listviewtable']/tr")
# It gives me many elements of tr tags
这里有两个问题:
1. 这种状况,如果要继续用selenium的话要如何解决?
2. 我在网路上找到可以透过browser.find_element_by_xpath(xpath).click()的方式,
去按「下一页」,但是在我想爬的这个网站里,
上一页跟下一页按钮的xpath我不知道怎麽分...有人可以提点一下吗?
或有其它的方式?
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 114.42.159.22
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1523377226.A.CB7.html
1F:→ s860134: 1. 我记得是因为 etree 在爬 html 结构时不计入 tbody 04/11 04:16
2F:→ s860134: 所以在 selenium 要用 table 耙仔带的时候要多一层tbody 04/11 04:20
3F:→ s860134: //table[@class='ms-listviewtable']/tbody/tr 04/11 04:21
4F:→ s860134: 你这个网站上一页下一页都有个 <td id="pagingWPQ2next"> 04/11 04:22
5F:→ s860134: 没有什麽无法区分的问题吧 04/11 04:22
6F:→ clsmbstu: 你给的xpath可以抓到东西,感谢! 04/11 09:54
7F:→ clsmbstu: 但本文两段都是用etree爬的,我还是不懂为什麽有此差别 04/11 09:55
8F:→ clsmbstu: 可以请你再解说详细一点吗? 04/11 09:55
9F:→ clsmbstu: 另外,就是因为上下页都有<td id="pagingWPQ2next">,我 04/11 09:56
10F:→ clsmbstu: 要怎麽控制我不是点到上一页而是下一页? 04/11 09:57
11F:→ clsmbstu: 等等,我发现上一页是<td id="pagingWPQ2prev">,抱歉 04/11 10:50