【问题标题】:Extract url links with python用python提取url链接
【发布时间】:2020-10-04 22:27:45
【问题描述】:

我想提取这个网页中所有soocer事件的url链接:https://www.coteur.com/cotes-foot.php

当我使用 xpath 逐个尝试匹配时,没关系,您可以在下面的代码中看到它,用于夹具 1 和夹具 2。 但是我想自动提取所有足球事件,以便我使用循环但它不起作用。似乎不可能在 xpath 函数中使用循环。如何解决这个问题?

#!/usr/bin/python3
# -*- coding: utf­-8 ­-*-

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)

fixture2 = driver.find_element_by_xpath("/html/body/div[3]/div/div[2]/div/div/div[2]/div/table/tbody/tr[23]/td[3]/a")
print(fixture2.text, '\n')

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

print(links)

driver.close()

【问题讨论】:

标签: python loops xpath href data-extraction


【解决方案1】:

当你把 'i' 放在引号内时,它会被解释为一个字符 - 而不是一个变量,所以我建议你试试这个:

while i <= 23:
    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 + 1

【讨论】:

    【解决方案2】:

    我明白了:

    hao@hao-ThinkPad-T420:~$ ./coteur2.py 
    Maccabi Netanya - Bnei Yehuda Tel Aviv
    Maritimo - Gil Vicente 
    
    [<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="2cb804be-ea18-4a5d-9fb9-75b306316126", element="c83b08b1-22ab-4454-95c2-cc6d133b926d")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="2cb804be-ea18-4a5d-9fb9-75b306316126", element="ffef9a50-56aa-480a-b144-59a1bb12e5c9")>]
    

    我正在寻找诸如fixture1 和fixture2 之类的事件名称

    【讨论】:

      猜你喜欢
      • 2021-02-01
      • 2018-12-25
      • 2020-10-06
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多