簡體   English   中英

使用 bs4 和 python 抓取鏈接

[英]Scraping links using bs4 and python

我正在尋找使用 bs4 解析網站中的鏈接。 我試圖避免使用正則表達式。

def generate_url(day, year, month):
   url = f"http://hockey-reference.com/boxscores/?year={year}&month={month}&day={day}"
   page = requests.get(url)
   soup = BeautifulSoup(page.content, 'lxml')
   return soup

soup = generate_url(13,2021,1)
html_links = soup.find_all('td', class_ = 'right gamelink')

我的結果是嵌入了 html 的列表...

[<td class="right gamelink">
<a href="/boxscores/202101130COL.html">F<span class="no_mobile">inal</span></a>
</td>,
<td class="right gamelink">
<a href="/boxscores/202101130EDM.html">F<span class="no_mobile">inal</span></a>
</td>,
<td class="right gamelink">
<a href="/boxscores/202101130PHI.html">F<span class="no_mobile">inal</span></a>
</td>,
<td class="right gamelink">
<a href="/boxscores/202101130TBL.html">F<span class="no_mobile">inal</span></a>
</td>,
<td class="right gamelink">
<a href="/boxscores/202101130TOR.html">F<span class="no_mobile">inal</span></a>
</td>]

提取這些鏈接的最佳方法是什么?

Append 您的代碼通過html_links迭代並從中獲取href

url = 'http://hockey-reference.com'
for html_link in html_links:
    link = html_link.findChild('a')['href']
    print(url + link)

如果您只想獲取包含“boxscores”的鏈接,請使用:

from bs4 import BeautifulSoup
import requests
import re

a = requests.get("https://www.hockey-reference.com/boxscores/?year=2021&month=1&day=13")
soup = BeautifulSoup(a.text, features="html.parser")

for link in soup.find_all('a', attrs={'href': re.compile("boxscores")}):
    print(link['href'])

Output:

在此處輸入圖像描述

有很多空鏈接,如果您只想要顯示 /boxscores/2021 的鏈接,只需將 re.compile 更改為“boxscores/2021”即可。

這使用 re 模塊在鏈接中查找“boxscores”,因此請務必import re

此外,如果您希望從網頁中獲取所有鏈接,請使用以下命令:

for link in soup.find_all('a', href=True):
    print(link['href'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM