求解答
import urllib.requestimport urllib.parse
import re
from bs4 import BeautifulSoup
import random
import time
def main():
## keyword = input("请输入关键词:")
keyword = urllib.parse.urlencode({"word":'猪八戒'})
url = ("http://baike.baidu.com/search/word?%s" % keyword)
iplist = ['113.28.90.67:9480']
proxy_support = urllib.request.ProxyHandler({'http':random.choice(iplist)})
opener = urllib.request.build_opener(proxy_support)
opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36')]
urllib.request.install_opener(opener)
response = urllib.request.urlopen(url)
html = response.read().decode('UTF-8')
soup = BeautifulSoup(html,"html.parser")
for each in soup.find_all(href=re.compile("view")):
content = ''.join()
url2 = ''.join(["http://baike.baidu.com",each["href"]])
response2 = urllib.request.urlopen(url2)
html2 = response2.read().decode('UTF-8')
soup2 = BeautifulSoup(html2,"html.parser") #从网页抓取数据
if soup2:
content = ''.join()
content = ''.join()
print(content)
time.sleep(3)
if __name__ == "__main__":
main()
运行结果总是:UnicodeEncodeError: 'ascii' codec can't encode characters in position 58-61: ordinal not in range(128)
求问题出在哪里了? 我在你的另一个帖子里回答过了,是转码问题,你自己去看一下吧 headers没配置吧,在headers里面配置一个user-agent fatinmidage 发表于 2021-12-29 10:07
headers没配置吧,在headers里面配置一个user-agent
opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36')]
配置了 myqf123 发表于 2021-12-29 12:30
opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHT ...
不好意思,看漏了。我用request模块是可以正常获取响应的
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62'}
url = 'http://baike.baidu.com/wikicategory/view?categoryName=恐龙大全'
res = requests.get(url,headers=headers) fatinmidage 发表于 2021-12-29 16:28
不好意思,看漏了。我用request模块是可以正常获取响应的
这个是可以的,到url2那儿就不行了 伏惜寒 发表于 2021-12-30 10:33
我在你的另一个帖子里回答过了,是转码问题,你自己去看一下吧
好的,非常感谢您!这是小甲鱼老师《零基础入门学习python》第55课的作业练习,我简单的改动了下,要的效果就是https://xxx.ilovefishc.com/forum/201605/17/155213x3trvluthvar6v3d.png 伏惜寒 发表于 2021-12-29 09:08
我在你的另一个帖子里回答过了,是转码问题,你自己去看一下吧
问题已解决,你的回答,让我知道了问题所在,非常感谢你,元旦快乐!!!
页:
[1]