【问题标题】:Iterating over click while scraping data using selenium and python在使用 selenium 和 python 抓取数据时迭代点击
【发布时间】:2018-07-25 00:33:47
【问题描述】:

我正在尝试从此网页中抓取数据

http://stats.espncricinfo.com/ci/engine/stats/index.html?class=1;team=5;template=results;type=batting

我需要从表中复制内容并将它们放入一个 csv 文件中,然后转到下一页并将这些页面的内容附加到同一个文件中。我可以抓取表格,但是当我尝试使用 selenium webdriver 的单击循环单击下一步按钮时,它会转到下一页并停止。这是我的代码。

    driver = webdriver.Chrome(executable_path = 'path')
    url = 'http://stats.espncricinfo.com/ci/engine/stats/index.html?class=1;team=5;template=results;type=batting'
def data_from_cricinfo(url):
    driver.get(url)
    pgsource = str(driver.page_source)
    soup = BeautifulSoup(pgsource, 'html5lib')
    data = soup.find_all('div', class_ = 'engineTable')
    for tr in data:
        info = tr.find_all('tr')
             # grab data

    next_link = driver.find_element_by_class_name('PaginationLink')
    next_link.click()
data_from_cricinfo(url)

是否可以使用循环单击所有页面的下一步并将所有页面的内容复制到同一个文件中?提前致谢。

【问题讨论】:

  • 程序停止,因为您在单击next_link 后没有在任何地方循环。想想你可以在哪里添加一个循环,以便为所有页面执行你想要的代码部分。
  • 对不起,我应该更清楚一点。这就是我在定义函数后如何添加循环的问题。我可以在 url 中的页码处循环,但我想知道是否有一种方法可以循环 click 函数,因为它可以用于即使在更改页面后 url 保持不变的情况。

标签: python selenium-webdriver web-scraping beautifulsoup


【解决方案1】:

您可以执行以下操作来遍历所有页面(通过Next 按钮)并解析表格中的数据:

from selenium import webdriver
from bs4 import BeautifulSoup

URL = 'http://stats.espncricinfo.com/ci/engine/stats/index.html?class=1;team=5;template=results;type=batting'

driver = webdriver.Chrome()
driver.get(URL)

while True:
    soup = BeautifulSoup(driver.page_source, 'html5lib')
    table = soup.find_all(class_='engineTable')[2]
    for info in table.find_all('tr'):
        data = [item.text for item in info.find_all("td")]
        print(data)

    try:
        driver.find_element_by_partial_link_text('Next').click()
    except:
        break

driver.quit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多