python - BeautifulSoup:“类型错误/属性错误:'NoneType'”
问题描述
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) 显示所有 href,(new_url) 显示所有新 url!
然而我不断得到TypeError: 'NoneType' object is not subscriptable
,并且没有任何内容添加到 urls 列表中。
如果我将其更改为a.get('href')
它说:AttributeError: 'NoneType' object has no attribute 'get'
(实际上不是谷歌,仅供参考)
这可能很简单,但我无法弄清楚。
谢谢!
解决方案
提供 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)
推荐阅读
- apache-spark - PySpark 在使用 table_name.colname 表示法加入后无法删除列,有没有更好的方法?
- javascript - 正则表达式未验证
- flutter - 使用 wrap 小部件使按钮在空格后对齐
- javascript - 未捕获的类型错误:无法在 javascript 中读取 null 的属性“追加”
- node.js - 写入本地主机 Postgres 返回臭名昭著的“42P01 parse_relation.c”错误
- javascript - 单击元素后工具提示没有隐藏(bootstrap v5.0)
- python - Pip 成功安装模块未找到:ImportError: No module named xlwt
- virtualenv - 对同一个 DAG 中的不同任务使用不同的 pandas 版本(气流)
- android - Android 5.1 选择键盘不起作用
- linux - 在 Arch linux 中更改 powerbutton 角色不起作用?