简体   繁体   English

使用 python、BeautifulSoup、Selenium 从表中抓取动态数据

[英]Scrape dynamic data from a table with python, BeautifulSoup, Selenium

I would like to scrape all the url links associated with the soccer games included in the table in this website .我想抓取与本网站表格中包含的足球比赛相关的所有 url 链接。

Here is the code:这是代码:

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()

When I scrape one match it returns the data I'm expecting.当我抓取一个匹配项时,它会返回我期望的数据。 However, when I tried to make a loop to get all the soccer games I run into a problem.但是,当我尝试循环获取所有足球比赛时,我遇到了问题。

Here is the result of the code:这是代码的结果:

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")>]

I wanted to get the first element, but I don't get what I was expecting.我想得到第一个元素,但我没有得到我所期望的。

This works well这很好用

    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)

I tried your code, here is the result:我试过你的代码,结果如下:

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

I prefer to use this way:我更喜欢用这种方式:

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)

Thanks for your help谢谢你的帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM