網(wǎng)頁爬蟲 - Python3.6 下的爬蟲總是重復(fù)爬第一頁的內(nèi)容
問題描述
問題如題:改成while,試了很多,然沒有效果,請(qǐng)教大家
# coding:utf-8# from lxml import etreeimport requests,lxml.html,osclass MyError(Exception): def __init__(self, value):self.value = value def __str__(self):return repr(self.value) def get_lawyers_info(url): r = requests.get(url) html = lxml.html.fromstring(r.content) # phones = html.xpath(’//span[@class='law-tel']’) phones = html.xpath(’//span[@class='phone pull-right']’) # names = html.xpath(’//p[@class='fl']/p/a’) names = html.xpath(’//h4[@class='text-center']’) if(len(phones) == len(names)):list(zip(names,phones))phone_infos = [(names[i].text, phones[i].text_content()) for i in range(len(names))] else:error = 'Lawyers amount are not equal to the amount of phone_nums: '+urlraise MyError(error) phone_infos_list = [] for phone_info in phone_infos:if(phone_info[0] == ''): info = '沒留姓名'+': '+phone_info[1]+'rn'else: info = phone_info[0]+': '+phone_info[1]+'rn'print (info)phone_infos_list.append(info) return phone_infos_listdir_path = os.path.abspath(os.path.dirname(__file__))print (dir_path)file_path = os.path.join(dir_path,'lawyers_info.txt')print (file_path)if os.path.exists(file_path): os.remove(file_path)with open('lawyers_info.txt','ab') as file: for i in range(1000):url = 'http://www.xxxx.com/cooperative_merchants?searchText=&industry=100&provinceId=19&cityId=0&areaId=0&page='+str(i+1)# r = requests.get(url)# html = lxml.html.fromstring(r.content)# phones = html.xpath(’//span[@class='phone pull-right']’)# names = html.xpath(’//h4[@class='text-center']’) # if phones or names:info = get_lawyers_info(url)for each in info: file.write(each.encode('gbk'))
問題解答
回答1:# coding: utf-8import requestsfrom pyquery import PyQuery as Qurl = ’http://www.51myd.com/cooperative_merchants?industry=100&provinceId=19&cityId=0&areaId=0&page=’with open(’lawyers_info.txt’, ’ab’) as f: for i in range(1, 5):r = requests.get(’{}{}’.format(url, i))usernames = Q(r.text).find(’.username’).text().split()phones = Q(r.text).find(’.phone’).text().split()print zip(usernames, phones)
相關(guān)文章:
1. docker - 各位電腦上有多少個(gè)容器啊?容器一多,自己都搞混了,咋辦呢?2. macos - mac下docker如何設(shè)置代理3. android studio總是在processes running好久4. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””5. java - 請(qǐng)問在main方法中寫成對(duì)象名.屬性()并賦值,與直接參參數(shù)賦值輸錯(cuò)誤是什么原因?6. MySQL數(shù)據(jù)庫中文亂碼的原因7. docker不顯示端口映射呢?8. dockerfile - 我用docker build的時(shí)候出現(xiàn)下邊問題 麻煩幫我看一下9. angular.js - 關(guān)于$apply()10. docker-compose 為何找不到配置文件?
