童鞋们,由于百度百科原网页的变化,也经过我自己这几天自己的缓慢摸索和不断尝试,终于尝试出了可以运行的代码,我在源代码的基础上更改了下,内容如下:
import urllib.request
import urllib.parse
import re
from bs4 import BeautifulSoup
def main():
keyword = input("请输入关键词:")
keyword = urllib.parse.urlencode({"word":keyword})
response = urllib.request.urlopen("https://baike.baidu.com/search/word?%s" % keyword) #此处将原网址http更新为https
html = response.read()
soup = BeautifulSoup(html, "html.parser")
print(soup.h2.text) # 此处增加了打印标题
print("\n") # 隔一行好看些
for each in soup.find_all(property=re.compile("description")): # 此处增加打印简介
print(each['content'])
print("\n下边打印相关链接\n")
for each in soup.find_all(href=re.compile("viewPageContent")): #此处将原来的“view”更改为“viewPageContent”
content = ''.join([each.text])
url2 = ''.join(["https://baike.baidu.com", each["href"]]) #此处将原网址http更新为https
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()
|