用 Python 抓取 URL 链接

Scrape URL links with Python

这是我的代码:

from selenium import webdriver
from bs4 import BeautifulSoup

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

links = driver.find_elements_by_xpath('//a[contains(@href, "match/cotes-")]')

driver.close()

我想从这个网站上抓取所有与足球比赛相关的 URL 链接:https://www.coteur.com/cotes-foot.php

我总是抓取包含足球比赛的所有 <a> 元素。但是我怎样才能提取链接到这些足球比赛的 URL?

试试这个:

import urllib.request, urllib.error, urllib.parse  #Import required modules
from bs4 import BeautifulSoup
import ssl

ctx=ssl.create_default_context()  #Check certificates, you can skip this for some 
                                   #websites 
ctx.check_hostname=False
ctx.verify_mode=ssl.CERT_NONE

userInput=input("Enter URL: ")
url=userInput if len(userInput)!=0 else "https://www.coteur.com/cotes-foot.php"

html=urllib.request.urlopen(url, context=ctx).read()
soup=BeautifulSoup(html, "html.parser")

tags=soup("a")                       #Find all html "a" tags, and print
for tag in tags:                 #The "a" tag is used to create link
    print(tag.get("href", None))

此程序打印它在页面上找到的所有链接

如果您只需要与足球相关的链接,您可以将最后一行修改为:

if 'soccer' in tag.get("href", None):
    print(tag.get("href", None))


您正在使用 find_elements_by_xpath 获取网络元素,您需要从中获取 href

from selenium import webdriver

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

links = []
for i in driver.find_elements_by_xpath('//a[contains(@href, "match/cotes-")]'):
    links.append(i.get_attribute('href'))

print(links)
driver.close()