python - 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 表的链接。关于如何进一步定义这一点的任何想法?
先感谢您。
解决方案
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
推荐阅读
- c# - 如何检索我的 BITS 作业的状态?
- regex - Apache URL 重写 UUID v1
- python - 如何查看查询集的所有属性?
- json - 使用自定义小部件覆盖 django JSONField
- css - 围绕其中心旋转 svg 路径(不是 svg 的中心)
- sql-server - 如何在行组和列组上使用嵌套聚合?
- flask - 如何编辑 WTForms FieldList 以删除列表中间的值
- python - Pyspark - 随着数据框变大而中断
- heroku - 手动输入路线时部署在 Heroku 上的 Angular 应用程序出现 404 错误
- python - 如何在 spaCy 中提取带有关键短语的句子