python - Beautifulsoup 的 Python 抓取问题
问题描述
使用 python 我试图获取目标 CSS 选择器的整个 html 代码。目标 html 代码如下所示,我想要整个代码:
<img class="card-img-top" src="/svg/2798804.svg" width="200px" height="200px" alt="kitten animal cat " style="user-select: auto;">
我的python代码:
with open("links.txt", "r") as a_file:
for line in a_file:
stripped_line = line.strip()
endpoint = stripped_line
start = stripped_line.find('/tag/') + 5
end = stripped_line.find('.html', start)
filename = stripped_line[start:end]
soup = BeautifulSoup(requests.get(endpoint).text)
completeName = os.path.join(workingpath, filename + ".txt")
with open(completeName, "w") as f_out:
for inp in soup.select('.card-img-top'):
print(inp["value"], file=f_out)
运行代码时出现此错误:
KeyError: 'value'
解决方案
BeautifulSoup 没有问题。value
属性在您的 html 片段中不存在(因为img
没有这样的属性,但是input
按照@KlausD 的建议拥有它。)
>>> inp.attrs
{'class': ['card-img-top'],
'src': '/svg/2798804.svg',
'width': '200px',
'height': '200px',
'alt': 'kitten animal cat ',
'style': 'user-select: auto;'}
标签的所有可能属性img
都可以在这里找到。
推荐阅读
- arrays - 在matlab中加载stl文件并转换为3D数组
- iis - Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException:请求正文太大
- reactjs - Typescript - React 组件中的“找不到名称”错误
- javascript - Docker + React-Scripts:慢 Bundle.js 下载
- angular - 加载时的ngx-toastr错误未找到角度firebase
- snakemake - snakemake中带有空格的文件
- excel - 评估单元格值是否是命名范围的一部分
- string - 如何将字符串转换为纯脚本中的字符列表?
- keras - 删除 Keras 中预训练的 VGG16 模型中的中间层
- python - 如何使用 PIL 裁剪多张图像?