from bs4 import BeautifulSoup
import bs4
import requests

def get_html(url):
    '''获取网页的html源代码的文本字符串'''
    try:
        kv = {'user-agent': 'Mozzila/5.0'}  # 设立头,提高爬取成功率
        r = requests.get(url, headers=kv, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""

def write_data(mylist, html):
    '''解析其源代码,并提取出信息,注意信息展现形式是表格形式,所以数据结构用二维列表'''
    soup = BeautifulSoup(html, "html.parser")
    '''此处为何不可用findall()函数呢,因为tr在tbody之外也存在
    而要提取的信息是tbody里面的tr里面的td'''
    for tr in soup.find('tbody').children:  # find, .children只会返回一个,是迭代类型,要循环遍历
    	if isinstance(tr, bs4.element.Tag):  # 检查其是否为bs4.element,.Tag类型,因为tr可能为\n等操作符他们也会被提取出来
        	tds = tr('td')  # list = t('a')即返回一个bs4.element.ResultSet对象,网上说bs4.element.ResultSet对象是
        # bs4.element.Tag对象的一个链表,实际上,list = t('a')这种模式就是返回一个以'a'标签为元素的列表
		t = [tds[0].string, tds[1].string, tds[2].string]  # 为什么是.string,因为要提取的信息在 > 里面 <,是非属性字符串类型
		mylist.append(t)
		
def get_file(mylist, num):
    '''将结果写入文件'''
    for i in range(num):
        u = mylist[i]
        with open('D:/test.txt', 'a') as datas:  # 以追加模式写入文本文件
            print(u, file=datas)
            
 if __name__ == '__main__':  # 直接相当于一个main函数,同using namespace std?
    url = 'http://www.zuihaodaxue.com/zuihaodaxuepaiming2018.html'
    html = get_html(url)
    ilist = []
    write_data(ilist, html)
    get_file(ilist, 20)

热爱生活,热爱编程
中国大学Mooc看的Python爬虫再优化及思考

相关文章:

  • 2021-10-27
  • 2021-12-10
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2021-09-16
猜你喜欢
  • 2021-08-25
  • 2022-12-23
  • 2021-05-12
  • 2021-06-21
  • 2021-11-30
相关资源
相似解决方案