首页 > 解决方案 > Python-Web抓取页面

问题描述

我的代码应该进入一个网站,浏览 2 个页面,并打印出每一行中的所有标题和 URL/href。

目前 - 我的代码很好地进入了这两个页面,但是它只打印出每页的第一个标题,而不是每行的每个标题。

该页面确实有一些 JavaScript,我想这可能就是为什么它没有在每一行中显示任何链接/urls/hrefs 的原因?理想情况下,id 喜欢打印每一行的 URL。

from selenium import webdriver
import time

driver = webdriver.Chrome()

for x in range (1,3):
    driver.get(f'https://www.abstractsonline.com/pp8/#!/9325/presentations/endometrial/{x}')
    time.sleep(3)
    page_source = driver.page_source
    eachrow=driver.find_elements_by_xpath("//li[@class='result clearfix']")
    for item in eachrow:
        title=driver.find_element_by_xpath("//span[@class='bodyTitle']").text
        print(title)

标签: pythonseleniumweb-scrapingbeautifulsoup

解决方案


您在driverfor 循环中使用意味着您正在搜索整个页面 - 因此您将始终获得相同的元素。

你想从每个搜索item

for item in eachrow:
    title = item.find_element_by_xpath(".//span[@class='bodyTitle']").text

此外,如上所述的行中没有“URL” - 当您单击一行时,该data-id属性将在请求中使用。

<h1 class="name" data-id="1989" data-key="">

向https://www.abstractsonline.com/oe3/Program/9325/Presentation/694发送请求


推荐阅读