網(wǎng)頁(yè)爬蟲(chóng) - Python3.6 下的爬蟲(chóng)總是重復(fù)爬第一頁(yè)的內(nèi)容
問(wèn)題描述
問(wèn)題如題:改成while,試了很多,然沒(méi)有效果,請(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 = '沒(méi)留姓名'+': '+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'))
問(wèn)題解答
回答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. golang - 用IDE看docker源碼時(shí)的小問(wèn)題2. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.3. 在windows下安裝docker Toolbox 啟動(dòng)Docker Quickstart Terminal 失敗!4. docker-machine添加一個(gè)已有的docker主機(jī)問(wèn)題5. Docker for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問(wèn)題6. docker-compose中volumes的問(wèn)題7. 我在centos容器里安裝docker,也就是在容器里安裝容器,報(bào)錯(cuò)了?8. 為什么我ping不通我的docker容器呢???9. docker容器呢SSH為什么連不通呢?10. docker不顯示端口映射呢?

網(wǎng)公網(wǎng)安備