Python3--baby网的数据爬取
生活随笔
收集整理的這篇文章主要介紹了
Python3--baby网的数据爬取
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
上代碼:
''' 本代碼用來爬取https://www.babyment.com/yingwenming/kaitou.php?start_letter=A&page=1的信息 '''import requests,csv,time,random from bs4 import BeautifulSoup from fake_useragent import UserAgent#獲取ip列表 def get_ip_list(): f=open('IP.txt','r') ip_list=f.readlines() f.close() return ip_list #從IP列表中獲取隨機IP def get_random_ip(ip_list): proxy_ip = random.choice(ip_list) proxy_ip=proxy_ip.strip('\n') proxies = {'http': proxy_ip} return proxies #功能:將信息寫入文件 def write_file(filePath,row): with open(filePath,'a+',encoding='utf-8',newline='') as csvfile: spanreader = csv.writer(csvfile,delimiter='|',quoting=csv.QUOTE_MINIMAL) spanreader.writerow(row) #解析baby網 def get_EnNames_list(url,ip_list):print('輸入進來的url為:{}'.format(url))#獲取隨機IP,headers防止ip被封headers = {'User-Agent':str(UserAgent().random)}proxies = get_random_ip(ip_list)try:req = requests.get(url=url,headers=headers,proxies=proxies,timeout=10)except:print('運行出錯10秒后重新運行')time.sleep(10)headers = {'User-Agent':str(UserAgent().random)}proxies = get_random_ip(ip_list)req = requests.get(url=url,headers=headers,proxies=proxies,timeout=10)#在利用find_all()注意要準確定位soup = BeautifulSoup(req.text,'lxml')content = soup.find('table',class_='table')content = content.find('tbody')content = content.find_all('tr')name = []#列表中沒有find_all()方法,故需要利用for語句for each in content:name.append(each.find_all('b')[0].get_text())return name#獲取baby網中所有的的英文名 def get_EnNames(letter,ip_list):for number in range(1,100):url = 'https://www.babyment.com/yingwenming/kaitou.php?start_letter={}&page={}'.format(letter,number)#一個網頁一個網頁的獲取我們需要的英文名name = get_EnNames_list(url,ip_list)#當page遇到最大值時,name就會為空,我們利用這一點進行切換,進入下一個字母的爬取if not name:print('{}開頭的英文名共{}個'.format(letter,number-1))breakfor each in name:#將一個列表分為多個列表,從而實現換行a=[]a.append(each)write_file('A-Z.csv',a)if __name__ == "__main__":ip_list = get_ip_list()for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':get_EnNames(letter,ip_list)總結
以上是生活随笔為你收集整理的Python3--baby网的数据爬取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python--音频文件分类代码
- 下一篇: Python--读取csv文件的整列