Beautiful Soup解析网页,Beautiful Soup的使用

 时间:2024-10-21 19:57:41

1、首先什么是网页,网页组建当我们访问网页时,我们的Web浏览器向Web服务器发出请求。然后,服务器发回文件,告诉浏览器如何为我们呈现页面。这些文件分为几种主要类型:HTML - 包含页面的主要内容。CSS - 添加样式以使页面看起来更好。JS - Javascript文件为网页添加交互性。图像 - 图像格式(如JPG和PNG)允许网页显示图片。以上这些都是构成网页的组建,如下打开beautiful soup安装库地址,这就是一个网页

Beautiful Soup解析网页,Beautiful Soup的使用

2、安装pip install beautifulsoup4pip install urllib2(没有装的话要安装)打开cmd,然后输入命令进行安装

Beautiful Soup解析网页,Beautiful Soup的使用

3、使用先读取我们要提取信息的页面 使用python的 urllib2from bs4 import BeautifulSoupimport urllib2html=urllib2.urlopen("http://127.0.0.1:8000/ceshi.html").read().decode('utf-8')print(html)或者import requestsfrom bs4 import BeautifulSouppage = requests.get(“http://127.0.0.1:8000/ceshi.html”) //page is response 对象soup = BeautifulSoup(page.content, 'html.parser')这两种方式都能取得html内容

Beautiful Soup解析网页,Beautiful Soup的使用

5、Beautifulsoup通过css解镙龟陛鹜析网页,我们在页面中给p标签加个样式类fontred,然后使用如下代码就可以实现p标签的内容缥熹嵛郦读出来from bs4 import BeautifulSoupfrom urllib2 import urlopenhtml = urlopen("http://127.0.0.1:8000/ceshi.html").read().decode('utf-8')soup=BeautifulSoup(html,features='lxml')print(soup.h1)soup = BeautifulSoup(html, features='lxml')month = soup.find_all('p', {"class": "fontred"})for m in month: print(m.get_text()) #输出p标签的内容

Beautiful Soup解析网页,Beautiful Soup的使用

7、beautifulsoup另一个好用的功能正则表达式匹配import reimg_links = soup.find_all("img", {"src": re.compile('.*?\.png')})for link in img_links: print(link['src'])通过匹配就可以把图片地址输出

Beautiful Soup解析网页,Beautiful Soup的使用
  • 植物大战僵尸2对战商店更新稀有新植物
  • 栾川 旅游攻略
  • 怎么去画一个可爱的表情头像
  • 湖南漂流比较好的地方
  • 热门搜索
    饮水思源的意思 沉浮与什么因素有关 lcm是什么意思 2万左右买什么车好 小心翼翼是什么意思 情不自禁的禁是什么意思 泥泞的意思 荷花一般什么时候开 报酬的意思 花都有什么好玩的地方