Python的BeautifulSoup库的使用

Python爬虫的BeautifulSoup库的使用

以下为爬去985高校的例子:

import requests
from bs4 import BeautifulSoup  #从bs4中引入BeautifulSoup库
import re

url="http://daxue.eol.cn/985.shtml"

r=requests.get(url)
r.encoding=r.apparent_encoding

soup=BeautifulSoup(r.text,"html.parser")#使用html.parser对爬取的源代码进行解析

for tr in soup.tbody:  #子标签可以使用for in从父标签中提取出来
    if len(tr)==9:     
        list=tr.contents #可以使用contents提取标签的子标签并生成列表
        print(list[1].text)
        print(list[3].string) #可以利用string,text,get_text提取标签中的文本
    if len(tr)==7:
        list=tr.contents
        print(list[1].string)




猜你喜欢

转载自blog.csdn.net/xinzhilinger/article/details/102727870