[問題] 同樣的xpath卻不一定能抓到東西?
我正想挑戰用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://www.ptt.cc/bbs/Python/M.1523377226.A.CB7.html
→
04/11 04:16,
7年前
, 1F
04/11 04:16, 1F
→
04/11 04:20,
7年前
, 2F
04/11 04:20, 2F
→
04/11 04:21,
7年前
, 3F
04/11 04:21, 3F
→
04/11 04:22,
7年前
, 4F
04/11 04:22, 4F
→
04/11 04:22,
7年前
, 5F
04/11 04:22, 5F
→
04/11 09:54,
7年前
, 6F
04/11 09:54, 6F
→
04/11 09:55,
7年前
, 7F
04/11 09:55, 7F
→
04/11 09:55,
7年前
, 8F
04/11 09:55, 8F
→
04/11 09:56,
7年前
, 9F
04/11 09:56, 9F
→
04/11 09:57,
7年前
, 10F
04/11 09:57, 10F
→
04/11 10:50,
7年前
, 11F
04/11 10:50, 11F