from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
def getTitle(url):
try:
html=urlopen(url)
except HTTPError as e:
return None
try:
bsObj=BeautifulSoup(html.read(),"html.parser")
title=bsObj.h1
except AttributeError as e:
return None
title=getTitle("https://mail.qq.com/")
为什么个代码title.h1 总是返回None
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
4条回答 默认 最新
冷寒越 2021-05-07 22:38关注??正常情况缺return 而且你这个代码没有输出打印函数吧,要的是输出title?
from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup def getTitle(url): try: html=urlopen(url) except HTTPError as e: return None try: bsObj=BeautifulSoup(html.read(),"html.parser") title=bsObj.h1 return title except AttributeError as e: return None title=getTitle("https://mail.qq.com/") print(title)本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报