【问题标题】:Scrape dynamic data from a table with python, BeautifulSoup, Selenium使用 python、BeautifulSoup、Selenium 从表中抓取动态数据
【发布时间】:2020-06-15 19:58:46
【问题描述】:

我想抓取与this website 中的表格中包含的足球比赛相关的所有网址链接。

代码如下:

from selenium import webdriver
from bs4 import BeautifulSoup

driver = webdriver.Firefox()
url = 'https://www.coteur.com/cotes-foot.php'
driver.get(url)

fixture1 = driver.find_element_by_xpath("/html/body/div[3]/div/div[2]/div/div/div[2]/div/table/tbody/tr[3]/td[3]/a")
print(fixture1.text)

links = []
i = 3
while i <= 6:
    fixture = driver.find_element_by_xpath("/html/body/div[3]/div/div[2]/div/div/div[2]/div/table/tbody/tr[" + str(i) + "]/td[3]/a")
    links.append(fixture)
    i = i + 3

print(links)

driver.close()

当我抓取一个匹配项时,它会返回我期望的数据。但是,当我尝试创建一个循环来获取所有足球比赛时,我遇到了问题。

这是代码的结果:

Betis Seville - Granada 74 Cf
[<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="0199958a-4d31-4a21-9856-8f8c3cc8ee05", element="158fcdaf-501f-41a4-9550-8a42543acc22")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="0199958a-4d31-4a21-9856-8f8c3cc8ee05", element="74e67896-fccb-48da-8eef-bbf8d9a6f3b3")>]

我想得到第一个元素,但没有得到我所期望的。

【问题讨论】:

    标签: python selenium loops web-scraping beautifulsoup


    【解决方案1】:

    这很好用

        from selenium import webdriver
    
        driver = webdriver.Firefox()
        driver.get("https://www.coteur.com/cotes-foot.php")
    
        links = driver.find_elements_by_xpath('//a[contains(@href, "match/cotes-")]')
    
        data = [l.text for l in links]
    
        print(data)
    

    【讨论】:

      【解决方案2】:

      我试过你的代码,结果如下:

      File "./coteur2.py", line 17
          data = [l.text for l in links]
          ^
      IndentationError: unexpected indent
      

      我更喜欢用这种方式:

      links = driver.find_elements_by_xpath('//a[contains(@href, "match/cotes-")]')
      
      n = 0
      while n < len(links):
         links[n] = links[n].text
         n = n + 1
      
      print(links)
      

      感谢您的帮助

      【讨论】:

      • 由于我的示例格式不正确,您遇到了错误。如果我的回答有帮助,请采纳为答案
      猜你喜欢
      • 2019-09-29
      • 2021-06-23
      • 1970-01-01
      • 2019-01-29
      • 2021-12-17
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多