python-3.x - 字符串切片 Python 请求 weblink
问题描述
我正在尝试使用 Python 脚本从网页获取链接。但我收到错误:
如果 links[0:4] == '/wiki' 和 links != '#':TypeError: 'NoneType' 对象不可下标。
你能帮忙吗?
from bs4 import BeautifulSoup
import requests
my_url = ('https://en.wikipedia.org/wiki/Kashmir')
response = requests.get(my_url)
page_soup = BeautifulSoup(response.content, "html.parser")
for link in page_soup.find_all('a'):
links = link.get('href')
if links[0:4] == '/wiki' and links != '#':
print("https://en.wikipedia.org/wiki" + links)
解决方案
您只需要以运算符开头的属性选择器
[href^='/wiki']
使用时select
,如果没有匹配项,您将获得一个空列表。
那是
links = ['https://en.wikipedia.org/wiki' + item['href'] for item in soup.select("[href^='/wiki']")]
推荐阅读
- javascript - 在 HTML 表格中使用 CSS 将复选框字体更改为粗体
- grafana - 如何在表格面板中放置两个不同的指标
- python - 将直方图函数扩展到具有任意间隙的重叠箱和箱?
- r - R中的协整分析:如何从`urca::cajorls`获取相关信息?
- python - 生成语法标签数据向量
- gcc - 如何将所需的组件添加到 crosstool-ng?
- ajax - jQuery Ajax 没有命中 Spring Boot API
- c# - 为什么这个自定义配置提供程序会错误地绑定数组元素?
- c# - 敏感信息的非用户可读文件
- terraform - 如何使用 Terraform 修改 Athena 的主要工作组配置?