首页 > 解决方案 > Python - 如何从网站拉回特定链接

问题描述

Python noob 传入,

我正在尝试从网站上抓取特定链接,尽管我正在撤回多个并且我不知道如何进一步定义代码以仅撤回我想要的那个。我相信问题是由于它们在 HTML 中是重复的“目标”


下面是一个 HTML 示例:

<ul><li><a href="Link1.pdf">Weekly Metrics</a></li>
<li><a rel="noreferrer noopener" href="Link2.xlsx" target="_blank">Monthly Website Statistics</a></li>
<li><a rel="noreferrerenter code here noopener" href="Link3.pdf" target="_blank">2020 Overview</a></li></ul>

我的尝试:

import requests
import pandas as pd
from bs4 import BeautifulSoup

raw_url = 'https://url1.com/'

r = requests.get(raw_url)

soup = BeautifulSoup(r.content, 'html.parser')

monthly_url = soup.find_all('a', target="_blank")

print(monthly_url)

********* 拉回 2 个结果 *********

monthly_url = (url.get('href')) #this would give me just the URL inside the <a /a> code I want.

我只想撤回“每月网站统计”Excel 表的链接。关于如何进一步定义这一点的任何想法?

先感谢您。

标签: pythonpython-3.xweb-scrapingbeautifulsoupjupyter-notebook

解决方案


from bs4 import BeautifulSoup

html = '''<ul><li><a href="Link1.pdf">Weekly Metrics</a></li>
<li><a rel="noreferrer noopener" href="Link2.xlsx" target="_blank">Monthly Website Statistics</a></li>
<li><a rel="noreferrerenter code here noopener" href="Link3.pdf" target="_blank">2020 Overview</a></li></ul>'''


soup = BeautifulSoup(html, 'lxml')
print(soup.select_one('a:-soup-contains(Monthly)')['href'])

输出:

Link2.xlsx

推荐阅读