BeautifulSoup find()问题
本帖最后由 fytfytf 于 2020-7-4 11:18 编辑import bs4
import urllib.request
import urllib.parse
import re
name=str(input('请输入搜索内容(以下搜索内容来自百度百科):'))
name=urllib.parse.quote(name)
head={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER'}
req=urllib.request.Request('https://baike.baidu.com/item/{}'.format(name),headers=head)
response=urllib.request.urlopen(req)
html=response.read().decode('utf-8')
soup=bs4.BeautifulSoup(html,'lxml')
jishu=0
print(soup.find('title').text)
print (soup.head.find(name=re.compile('description')))#出错代码
标红的这句抓百度百科,返回值永远是都是None,明明是按照格式的{:10_266:}
这样试试吧:
import bs4
import urllib.request
import urllib.parse
import re
name=str(input('请输入搜索内容(以下搜索内容来自百度百科):'))
name=urllib.parse.quote(name)
head={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER'}
req=urllib.request.Request('https://baike.baidu.com/item/{}'.format(name),headers=head)
response=urllib.request.urlopen(req)
html=response.read().decode('utf-8')
soup=bs4.BeautifulSoup(html,'lxml')
jishu=0
print(soup.find('title').text)
print (soup.head.find_all('meta')['content']) find函数里name参数填的是节点的名字,不是节点属性。也是巧了这个属性叫name,让你混淆了。
print(soup.head.find(name='meta', attrs={'name': 'description'}))
页:
[1]