【问题标题】:How do I fix this attribute error python?如何修复此属性错误python?
【发布时间】:2021-08-14 11:10:57
【问题描述】:

我的代码有问题。我正在尝试提取本网站 (https://www.local.ch/en/q/geneve/employment%20agency?slot=yellow) 上列出的职位,其中包含公司名称及其信息的链接。第一部分有效,我可以打印所有名称,但是打印到其信息的链接会给我错误:

Traceback (most recent call last):
  File "main.py", line 20, in <module>
    href = (links.get("href"))
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/bs4/element.py", line 921, in __getattr__
    raise AttributeError(
AttributeError: 'NavigableString' object has no attribute 'get'

这是我的代码:

print("Hello, welcome to local job in geneva finder")

import requests
from bs4 import BeautifulSoup

url = "https://www.local.ch/en/q/geneve/employment%20agency?slot=yellow"

response = requests.get(url)
html = response.text

soup = BeautifulSoup(html, "html.parser")
names = soup.findAll("h2")
for name in names:
    print(name.text)

link = soup.find("a")
for links in link:
    href = (links.get("href"))
    if href.startswith("https://www.local.ch/en/d/geneve/1204/recruiting"):
        print(href)

【问题讨论】:

  • for links in name: - 应该是for links in link:吗?

标签: python web-scraping attributeerror


【解决方案1】:

使用findAll提取所有&lt;a&gt;标签。

links = soup.findAll("a")

迭代链接而不是名称的循环以从所有 &lt;a&gt; 标记中获取 href
link.get("href") 可以在&lt;a&gt; 标签中找不到 href 的情况下也返回 None。所以写一个条件来检查天气是否为None。

完整代码:

print("Hello, welcome to local job in geneva finder")
import requests
from bs4 import BeautifulSoup

url = "https://www.local.ch/en/q/geneve/employment%20agency?slot=yellow"

response = requests.get(url)
html = response.text

soup = BeautifulSoup(html, "html.parser")
names = soup.findAll("h2")
for name in names:
    print(name.text)

links = soup.findAll("a")
for link in links:
    href = link.get("href")
    if href:
        if href.startswith("https://www.local.ch/en/d/geneve/1204/recruiting"):
            print(href)

【讨论】:

  • 我正在尝试打印链接以获取有关列出的所有作业的更多信息。当我运行程序时,它只显示列出的链接第一个作业。
  • 没明白你的意思。你想从所有页面中提取信息吗?然后使用分页。使用循环更改每个页面的链接...
  • 我想取网站上列出的每个职位的名称,并附上每个职位的链接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
  • 2021-01-13
相关资源
最近更新 更多