python - 如何以表格的形式进行抓取,使列表变得均匀

标签 python python-3.x selenium selenium-webdriver web-scraping

我正在使用 Selenium Webdriver (Python 3.0) 从这个 website 中抓取数据.然而,所有数据都被正确地抓取了,它以列表的形式抓取,这意味着有 127 个团队和赔率以及 129 个 Hrefs。不幸的是,这意味着 Href 不在团队旁边,并且 excel 中的赔率正确。有办法解决这个问题吗?

我附上了屏幕截图,我的代码在下面。有没有一种方法可以将其调整为作为表格进行抓取,以便它知道在没有团队和赔率可见的情况下不抓取 Href?我正在从具有此功能的 Winautomation 迁移到 Selenium。

https://ibb.co/kMC0mk - 图片显示为什么 Href 不在球队和赔率旁边 https://ibb.co/hh4rsQ - Excel 的外观。

import time
from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'C:\ad\chromedriver.exe')
driver.set_window_size(1024, 600)
driver.maximize_window()


driver.get('https://www.bluebet.com.au/sports/Soccer/100')

SCROLL_PAUSE_TIME = 0.5

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

time.sleep( 15 )   

#Odds
langs = driver.find_elements_by_css_selector(".table-grid__row:nth-child(1) .headline-wrap")
for lang in langs:
    print (lang.text)

time.sleep( 10 )

#link
langs = driver.find_elements_by_css_selector("div.ctr--epsilon.soft > a[href*='/sports/Soccer/']")
for lang in langs:
    print (lang.get_attribute('href'))

time.sleep( 10 )

#Team
langs = driver.find_elements_by_css_selector(".table-grid__row:nth-child(1) .place-bet__odds")
for lang in langs:
    print (lang.text)

最佳答案

我同意@ChellWheatly 的观点,找不到使用 CSS 来实现这一点的方法。

试试这个 xpath 选择器只抓取有内容的“Hrefs”:

//a/ancestor::div[contains(@class, 'table-grid')]/preceding-sibling::div[contains(@class, 'ctr--epsilon')]//a

(我已经在真实页面上用 this chrome extension 测试过了)

关于python - 如何以表格的形式进行抓取,使列表变得均匀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45901264/

相关文章:

python - 如何从网站中提取信息?

python - 将 Python 代码分发为 Mac/Windows/Linux 的可执行文件

python - 无法在 http ://www. dropzonejs.com 上使用 python selenium webdriver 上传文件

python - 如何使用scrapy抓取xml url

python - Python 字典错误 : str object has no attribute append

python - 运行 for 循环并跳过股票 'KeyError' : Date

php - captureScreenshotOnFailure 不工作,损坏

java - 无法在 selenium Web 驱动程序中使用 Javascript 设置选择值

python - 使用 pyserial 识别给定 USB VID 和 PID 的 USB 转串口

python - 产生子组合