簡體   English   中英

如何修復此屬性錯誤 python?

[英]How do I fix this attribute error python?

我的代碼有問題。 我正在嘗試提取本網站 ( 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)

使用findAll提取所有<a>標記。

links = soup.findAll("a")

迭代鏈接而不是名稱的循環以從所有<a>標記中獲取href
link.get("href")<a>標簽中找不到 href 的情況下也可以返回 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM