网络编程
位置:首页>> 网络编程>> Python编程>> urllib和BeautifulSoup爬取 * 的词条简单实例

urllib和BeautifulSoup爬取 * 的词条简单实例

作者:powerpoint_2016  发布时间:2023-10-25 21:46:59 

标签:python,爬虫,urllib,beautifulsoup

本文实例主要实现的是使用urllib和BeautifulSoup爬取 * 的词条,具体如下。

简洁代码:


#引入开发包
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
#请求URL并把结果用UTF-8编码
resp=urlopen("https://zh.wikipedia.org/wiki/Wikipedia:%E9%A6%96%E9%A1%B5").read().decode("utf-8")
#使用BeautifulSoup去解析
soup=BeautifulSoup(resp,"html.parser")
#print(soup)
#获取所有以/wiki/开头的a标签的href属性
listUrl=soup.findAll("a",href=re.compile("^/wiki/"))
#输出所有词条对应的名称和URL
for link in listUrl:
 if not re.search("\.(jpg|JPG)$",link["href"]):
   print(link.get_text(),"<----->","https://zh.wikipedia.org"+link["href"])

运行结果:

urllib和BeautifulSoup爬取 * 的词条简单实例

总结

总的来说,Python是简洁而又强大的,调用几个库,就能实现其他语言一大堆代码才能实现的功能。

来源:http://blog.csdn.net/m0_38066258/article/details/77751909

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com