网页爬虫 - Python3.6 下的爬虫总是重复爬第一页的内容
问题描述
问题如题:改成while,试了很多,然没有效果,请教大家
# 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)
相关文章:
1. javascript - 微信小程序中设置头像 里面的图片路径是怎么解决的 我把接口生成的路径存到数据库中 2次访问时就显示不出来了2. javascript - 我写的href跳转地址不是百度,为什么在有的机型上跳转到百度了,有的机型跳转正确3. angular.js - react的redux和vue的vuex,angular呢4. angular.js - vue/react 渲染内容抖动5. 新手学习vue和node.js的困惑6. python - 如何用openpyxl在现有的excel文件中写入数据7. objective-c - IOS 如何实现网易云音乐选择头像的ImagePicker8. 我设置的背景怎么显示不出来9. android - 有没有人做过类似支付宝那种汇率换算功能的?10. 在使用Vim编辑Python这类的脚本时,如何在下方嵌入一个小小的shell,以方便观察输出结果?
