Python 为什么soup.find(';title';)在BeautifulSoup中不返回任何内容?
我正在使用请求和beautifulsoup解析url的响应内容 但是,当我尝试在Beautifulsoup中使用Python 为什么soup.find(';title';)在BeautifulSoup中不返回任何内容?,python,python-3.x,python-2.7,beautifulsoup,python-requests,Python,Python 3.x,Python 2.7,Beautifulsoup,Python Requests,我正在使用请求和beautifulsoup解析url的响应内容 但是,当我尝试在Beautifulsoup中使用soup.find('title')解析响应并查找标题时,它没有向我返回任何信息。甚至一个错误都没有 它只是什么也不做。正在执行soup.find()上方的print语句。但不是在if和if之后 import requests, os from bs4 import BeautifulSoup lis=[ 'https://oxhp-member-elr.uhc.com/Mem
soup.find('title')
解析响应并查找标题时,它没有向我返回任何信息。甚至一个错误都没有
它只是什么也不做。正在执行soup.find()上方的print语句。但不是在if和if之后
import requests, os
from bs4 import BeautifulSoup
lis=[
'https://oxhp-member-elr.uhc.com/Member/MemberPortal/'
]
for element in lis:
resp = requests.get(element)
if resp.status_code == 200:
cont = resp.content.decode('UTF-8')
try:
soup = BeautifulSoup(cont, "html.parser")
print('Now')
if soup.findAll('title')[0].get_text() is None:
print('Hi')
print('after if')
print(element.ljust(element_length), resp.status_code, soup.find('title').text)
except:
pass
我尝试了“soup.find('title')。text
。但这也不起作用
有人能告诉我我的代码出了什么问题吗?您正在使用try块处理异常,但什么也不做(只是
传递
),这就是您没有看到错误消息的原因。如果出现不在try块内的错误,默认行为是中断代码并打印堆栈跟踪。如果try块内发生错误,代码将跳转到except块,接下来发生什么将由您决定。不会自动打印任何错误消息
如果尝试打印错误或在循环中添加Soup对象的打印语句,您将看到以下内容:
try:
soup = BeautifulSoup(cont, "html.parser")
print('Now')
# Print the soup object
print(soup)
if soup.findAll('title')[0].get_text() is None:
print('Hi')
print('after if')
#print(element.ljust(element_length), resp.status_code, soup.find('title').text)
except Exception as error:
# Handle the exception with some information.
print(error)
pass
输出
Sorry, we are unable to process your request at this time.
对于print语句,错误消息如下所示:
list index out of range
基本上,您无法解析URL,因此尝试使用if语句中的
[0]
访问空数组,这会引发错误。删除try-except并发布错误消息。也可能是请求无效,并且返回的不是200