首页 > 解决方案 > 字符串切片 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)

标签: python-3.xbeautifulsouppython-requests

解决方案


您只需要以运算符开头的属性选择器

[href^='/wiki']

使用时select,如果没有匹配项,您将获得一个空列表。

那是

links = ['https://en.wikipedia.org/wiki' + item['href'] for item in soup.select("[href^='/wiki']")]

推荐阅读