我正在尝试用下面的代码抓取一个HTML页面:
driver = webdriver.Chrome()
driver.get(url)
try:
element = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.CLASS_NAME,
"myclass")))
html = driver.page_source
soup = bs(html, "lxml")
print(html)
dynamic_text = soup.find_all("div", {"class": "myclass"})
except:
print("Couldnt locate element")html页面已打开,但在IDE控制台中我看到了except消息。看起来,没有找到包含class_name "myclass“的div。然而,当我检查我得到的html页面时,我在那里看到了带有该类名的div。
HTML中的div:
<div role="radio" data-ng-attr-id="{{radioId}}" data-ng-attr-tabindex="{{directToShow === strVm.data.selectedDirectToShow ? '0' : '-1'}}" data-ng-attr-aria-checked="{{directToShow === strVm.data.selectedDirectToShow ? 'true' : 'false'}}" class="trainBasicInfo ng-scope" data-ng-if="directToShow.date == undefined" data-ng-click="strVm.onSelectDirectToShow(directToShow, $event)" data-ng-class="{'active': directToShow === strVm.data.selectedDirectToShow}" id="railRadio_423" tabindex="-1" aria-checked="false">我在WebDriverWait中添加了注释,然后看到了print(html)命令的输出。在打印的输出中,我看不到div,但是当我检查打开的chrome页面时,我可以看到div。
发布于 2019-07-01 00:51:18
我不知道你用的是哪个class,但是用浏览器检查的时候用的类,和源页的类是不一样的:DOM是由JavaScript在加载页面源代码后修改的。
试试这个:
driver = webdriver.Chrome()
driver.get(url)
try:
elements = WebDriverWait(driver, 20).until(
EC.presence_of_all_elements_located((By.XPATH,
"//div[contains(@class, 'trainBasicInfo ng-scope')]")))
# By.XPATH gives more flexibility
for element in elements:
print(element)
except:
# print("Couldnt locate element")
raise # except with no Exception specified is prohibited使用Chrom Dev工具从inspect获得:

来自view-source:https://www.rail.co.il/pages/trainsearchresultnew.aspx?FSID=4170&TSID=5000&Date=20190630&Hour=1000&IOT=true&IBA=false&TSP=1561835762832:

输出如下:
30.06.2019 יום א'
00:46
רציף 1
19:12
19:58
רכבת 687
החלפה 19:44
תל אביב - ההגנה - רציף 3
רכבת 425
30.06.2019 יום א'
00:44
רציף 1
19:27
20:11
רכבת 689
החלפה 19:56
תל אביב - ההגנה - רציף 3
רכבת 529
30.06.2019 יום א'
00:42
רציף 1
19:57
20:39
רכבת 691
החלפה 20:26
תל אביב - ההגנה - רציף 3
רכבת 979
30.06.2019 יום א'
00:44
רציף 1
20:27
21:11
רכבת 693
החלפה 20:56
תל אביב - ההגנה - רציף 2
רכבת 531
30.06.2019 יום א'
00:44
רציף 1
21:27
22:11
רכבת 8695
החלפה 21:49
תל אביב - סבידור מרכז - רציף 3
רכבת 533发布于 2019-07-01 00:08:33
如果你正在使用Selenium,你应该尝试这样做:
driver = webdriver.Chrome()
driver.get(url)
element = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.CLASS_NAME,"myclass")))
html = driver.page_source
dynamic_text = driver.find_elements_by_xpath('//div') #this will be a list of all divs on the page, they all will be selenium object还要记住,根据您的驱动程序配置,页面上可能没有某些脚本生成的内容
https://stackoverflow.com/questions/56826239
复制相似问题