用python提取网址链接

问题描述 投票:1回答:1

我想在这个网页上提取所有soocer事件的url链接。 https:/www.coteur.comcotes-foot.php

当我使用xpath逐场比赛时,它是正常的,你可以在我下面的fxture1和fxture2的代码中看到它,但是我想自动提取所有的足球事件,所以我使用了一个循环,但它不工作。似乎在xpath fonction中不能使用循环。如何解决这个问题?

#!/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个回答
0
投票

当你把'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

0
投票

我得到的是:

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。

© www.soinside.com 2019 - 2024. All rights reserved.