|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import urllib.request
from bs4 import BeautifulSoup
def getHtml(url):
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html,'lxml')
print(soup.prettify())
if __name__ == '__main__':
getHtml("https://gleaming.cn/2021/02/13/Why-two-survivor-spaces/")
上面这一段代码我可以得到正确的结果
而下面这一段我改用requests库,但是运行结果是http error 418,在网上查到的解决方案都是千篇一律要加headers,但是我代码中原本就有,求大神解答我的问题
from bs4 import BeautifulSoup
import requests
def gethtml(url):
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
def parsehtml(html):
soup = BeautifulSoup(html, 'lxml')
print(soup.prettify())
if __name__ == '__main__':
url = "https://gleaming.cn/2021/02/13/Why-two-survivor-spaces/"
html = gethtml(url)
parsehtml(html)
|
|