BeautifulSoup:“TypeError/AttributeError:'NoneType'”

2024-03-28 11:02:32 发布

您现在位置:Python中文网/ 问答频道 /正文

import requests
from bs4 import BeautifulSoup

url = 'https://joboutlook.gov.au/A-Z'

r = requests.get(url)
c = r.content
soup = BeautifulSoup(c, 'html.parser')

urls = []
h4s = soup.find_all('h4')
for h4 in h4s:
    a = h4.find('a')
    print(a)
    href = a['href']
    print(href)
    new_url = f'https://joboutlook.gov.au/{href}'
    print(new_url)
    urls.append(new_url)
urls

指纹都有用。(a) 显示所有的'a'标签,(href)显示所有的hrefs,(new\u url)显示所有的新url!你知道吗

但是我一直得到TypeError: 'NoneType' object is not subscriptable,没有任何东西被添加到url列表中。你知道吗

如果我把它改成a.get('href'),它会说:AttributeError: 'NoneType' object has no attribute 'get'

(其实不是谷歌,仅供参考)

可能很简单,但我搞不懂。你知道吗

谢谢!你知道吗


Tags: httpsimporturlnewgetrequestsurlsh4
2条回答

提供if条件,if锚定标记可用,然后获取href并附加它。你知道吗

import requests
from bs4 import BeautifulSoup
soup=BeautifulSoup(requests.get("https://joboutlook.gov.au/A-Z").text,'html.parser')
urls = []
h4s = soup.find_all('h4')
for h4 in h4s:
    a = h4.find('a')
    if a:
     href = a['href']
     #print(href)
     new_url ='https://joboutlook.gov.au/{}'.format(href)
     #print(new_url)
     urls.append(new_url)

print(urls)

更改为使用一个选择器,该选择器对具有h4属性的子元素进行筛选。你知道吗

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://joboutlook.gov.au/A-Z')
soup = bs(r.content, 'lxml')
links = [f'https://joboutlook.gov.au/{item["href"]}' for item in soup.select('h4 > [href]')]

您可以假设所有a标记都有href(稍微快一点,不太健壮,但可能很好)

links = [f'https://joboutlook.gov.au/{item["href"]}' for item in soup.select('h4 > a')]

相关问题 更多 >