今日代码(20201003)--简单爬虫
生活随笔
收集整理的這篇文章主要介紹了
今日代码(20201003)--简单爬虫
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼筆記,僅供參考
利用python爬取安徽省高校名單
因為工作需要,所以我爬取了安徽省高校的名單,并將其保存在csv文件中:
# -*- coding: utf-8 -*-# -*- coding: utf-8 -*-import requests from lxml import etree from fake_useragent import UserAgent import time import csvclass SchoolSpider:def __init__(self):self.url = 'http://www.gx211.com/gxmd/gx-ah.html'def get_ua(self):return UserAgent().randomdef get_page(self):headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0)'}res = requests.get(self.url, headers = headers)html = res.content.decode('utf-8')print('url:', res.url)print('code:', res.status_code)#print(html)self.get_school_list(html)def get_school_list(self, html):html_parse = etree.HTML(html)xpath = '//table//td[@class="td1"]/a/text()'s_list = html_parse.xpath(xpath)#print(s_list)self.write_ip(s_list)def write_ip(self, school_list):with open('./output/my_school_name.csv', 'w', newline = '', encoding = 'utf-8') as f:writer = csv.writer(f)writer.writerow(['school'])for item in school_list:writer.writerow([item])def main(self):self.get_page()if __name__ == '__main__':start = time.time()spider = SchoolSpider()spider.main()end = time.time()print('執行時間:%.2f' % (end-start))部分結果:
school 安徽大學 中國科學技術大學 合肥工業大學 安徽工業大學 安徽理工大學 安徽工程大學 安徽農業大學 安徽醫科大學 蚌埠醫學院 皖南醫學院 安徽中醫藥大學 安徽師范大學 阜陽師范大學 安慶師范大學總結
以上是生活随笔為你收集整理的今日代码(20201003)--简单爬虫的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 输入法管理器妙用 隐藏不喜欢的输入法
- 下一篇: Django从理论到实战(part51)