源代码:
import requests
from bs4 import BeautifulSoup
try:
kv = {'user_Agent':'Mozilla/5.0'}
demo = requests.get('http://www.ugirl.com',headers = kv)
demo.raise_for_status()
soup = BeautifulSoup(demo,'html.parser')
print(soup.prettify()) #以html文本格式打印
except:
print('解析错误')
遇到错误:
错误原因:
因为这里的demo是requests对象,无法用BeautifulSoup解析,可以在demo后面加上content。
import requests
from bs4 import BeautifulSoup
try:
kv = {'user_Agent':'Mozilla/5.0'}
demo = requests.get('http://www.ugirl.com',headers = kv)
demo.raise_for_status()
soup = BeautifulSoup(demo.content,'html.parser')
print(soup.prettify()) #以html文本格式打印
except:
print('解析错误')
正确运行: