|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import re
- import urllib.request
- import urllib.parse
- from bs4 import BeautifulSoup
- def main():
- word = input('请输入搜索关键字: ')
- key = urllib.parse.urlencode({'word':word}).encode('utf-8')
- response = urllib.request.urlopen('http://baike.baidu.com/search/word?%s' % key)
- html = response.read().decode('utf-8')
- soup = BeautifulSoup(html, 'html.parser')
- for each in soup.find_all(href=re.compile('view')):
- content = ''.join([each.text])
- url2 = ''.join(['http://baike.baidu.com/', each['href']])
- response2 = urllib.request.urlopen(url2)
- html2 = response2.read()
- soup2 = BeautifulSoup(html2)
- if soup2.h2:
- content = ''.join([content, soup2.h2.text])
- content = ' '.join([content, '->', url2])
- print(content)
- if __name__ == '__main__':
- main()
复制代码
UnicodeEncodeError: 'ascii' codec can't encode characters in position 37-40: ordinal not in range(128)
为什么运行结果会出错?怎样避免这类错误?
- import re
- import urllib.request
- import urllib.parse
- from bs4 import BeautifulSoup
- def main():
- word = input('请输入搜索关键字: ')
- key = urllib.parse.urlencode({'word':word}).encode('utf-8')
- response = urllib.request.urlopen('http://baike.baidu.com/search/word?%s' % key)
- html = response.read().decode('utf-8')
- soup = BeautifulSoup(html, 'html.parser')
- for each in soup.find_all(href=re.compile('view')):
- content = ''.join([each.text])
- url2 = ''.join(['https://baike.baidu.com/', urllib.parse.quote(each['href'])])
- response2 = urllib.request.urlopen(url2)
- html2 = response2.read()
- soup2 = BeautifulSoup(html2, 'html.parser')
- if soup2.h2:
- content = ''.join([content, soup2.h2.text])
- content = ' '.join([content, '->', url2])
- print(content)
- if __name__ == '__main__':
- main()
复制代码
|
|