python - 如何处理来自 BeatifulSoup 的输出数据?具体来说,如何拆分 URL 和锚点?
问题描述
我有这个测试代码来从网页中提取反向链接。但是我还没有找到一个好的解决方案来专门提取 URL 和锚点,以及标签的附加属性。
请允许我解释得更彻底。假设我有 3 个网页需要检查。site.com/a/、site.com/b/ 和 site.com/c/。对于每个网页,我都有以下带有此代码的输出:
1. [<a data-wpel-link="external" href="https://example.com/" rel="nofollow" target="_blank">anchor-example-1</a>]
2. [<a href="\'https://example.com/\'" rel="\'nofollow\'" target="\'_blank\'">anchor-example-2</a>]
3. [<a href="https://example.com/" rel="nofollow">anchor-example-3</a>]
拆分提取的最佳方法是什么,所以我有以下输出,比如示例 #1?
Linked URL: https://example.com/
Anchor: anchor-example-1
Rel: nofollow
此外,如示例 #2 所示,一些网站倾向于在代码中添加一些垃圾(?)。
href="\'https://example.com/\'"
如何摆脱诸如\'和其他有时可能会损坏输出数据的东西?
from bs4 import BeautifulSoup
import requests
import re
with open('input.txt') as input_data:
for line in input_data:
check_url = line.rstrip('\n')
data = requests.get(check_url, headers={'User-Agent': 'Mozilla/5.0'})
data.encoding = 'ISO-8859-1'
soup = BeautifulSoup(str(data.content), 'html.parser')
backlink = soup.find_all('a', attrs={'href': re.compile('example.com')})
print('Backlink: ', backlink, '\n')
提前致谢,祝您节日快乐!
解决方案
试试这样的:
from bs4 import BeautifulSoup
html = """<a data-wpel-link="external" href="https://example.com/" rel="nofollow" target="_blank">anchor-example-1</a>
<a href="\'https://example.com/\'" rel="\'nofollow\'" target="\'_blank\'">anchor-example-2</a>
<a href="https://example.com/" rel="nofollow">anchor-example-3</a>
"""
soup = BeautifulSoup(html)
for n in soup.find_all('a'):
print ('Linked : '+ n.get('href'))
print ('Rel : '+''.join(n.get('rel')))
print('Anchor : '+n.text)
结果 :
Linked : https://example.com/
Rel : nofollow
Anchor : anchor-example-1
Linked : 'https://example.com/'
Rel : 'nofollow'
Anchor : anchor-example-2
Linked : https://example.com/
Rel : nofollow
Anchor : anchor-example-3
推荐阅读
- android - 由于计费错误,谷歌将自动完成关闭
- php - 下载具有给定名称的 fpdf?
- php - 是否有内置的 PHP 函数来检查给定的字符串是否是保留关键字?
- java - 我们可以在全局状态存储恢复期间调用处理器吗?
- excel - 如何将项目从 Excel 工作表行添加到 ComboBox?
- javascript - 如何获取下载视频的文件大小以显示加载过程,如 js 中的 1.2mb/3mb?
- ruby-on-rails - 在 ruby 葡萄 API 的参数中测试自定义验证器的存在
- qt - 无法创建路径为“*.qml”的组件
- php - 如何使用 sql 数据库在 php 中进行用户特定登录?
- angular - 如何将我的标签与角材料中的按钮对齐?