首页 > 解决方案 > 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'

标签: pythonweb-scrapingbeautifulsouppython-requests

解决方案


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都可以在这里找到。


推荐阅读