python3 [爬虫实战] selenium + requests 爬取安居客

来源:互联网 发布:plc用c语言编程 编辑:程序博客网 时间:2024/05/07 19:06

很简单,这里是根据网友的求助爬取的安居客上的一个页面的全部地区名称跟链接

因为她用的scrapy框架,感觉有些大才小用了,所以就直接用了一个requests库,selenium 和xpath进行一整页数据的爬取

我们爬取的网站:https://www.anjuke.com/sy-city.html

获取的内容:包括地区名,地区链接:

安居客详情

1 一开始直接用requests库进行网站的爬取,会访问不到数据的, 会直接出现 访问的页面出现错误的信息。(ps:这里就暂时不打印出来了。)

2 因为一直报错,脑瓜子不知道怎么的就想到了selenium 这个框架,可能是爬安居客之前用selenium 爬取了天猫的商品内容吧。

3 selenium 的使用,我的博客上有说过:

http:/blog.csdn.net/xudailong_blog/

4 现在贴上代码片段:

# -*- coding: utf-8 -*-# @Time    : 2017/9/19 21:36# @Author  : 蛇崽# @Email   : 17193337679@163.com# @File    : anjuke.py 安居客房产网import requestsimport refrom bs4 import BeautifulSoupimport csvimport timeimport threadingfrom lxml import etreefrom selenium import webdriverfrom openpyxl import Workbooknum0 = 1  # 用来计数,计算爬取的书一共有多少本baseurl = 'https://www.anjuke.com/sy-city.html'wb = Workbook()ws = wb.activews.title = '安居客'ws.cell(row=1, column=1).value = '城市名称'ws.cell(row=1, column=2).value = '城市链接'def gethtml():    chromedriver = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"    browser = webdriver.Chrome(chromedriver)    browser.get(baseurl)    time.sleep(5)    js = 'window.scrollBy(0,3000)'    browser.execute_script(js)    js = 'window.scrollBy(0,5000)'    browser.execute_script(js)    html = browser.page_source    return htmldef saveinfos(authorother):    global num0    nums = 0    for ver_info in authorother:        num0 = num0 + 1        ws.cell(row=num0, column=1).value = ver_info[0]        ws.cell(row=num0, column=2).value = ver_info[1]        nums += 1        print('爬取成功 ' + str(nums))    wb.save('安居客' + '.xlsx')    passdef parseHotBook(html):    # 作者 (豆瓣用户,简书)    print(html)    print('*'*20)    # commentlist = html.xpath("/html/body/div[3]/div")    # 作者 (豆瓣用户,简书)    regAuthor = r'.*?<a href="(.*?)</a>'    reg_author = re.compile(regAuthor)    authorother = re.findall(reg_author, html)    global num0    nums = 0    for info in authorother:        verinfo = info.split('">')        print(verinfo[0],verinfo[1].replace('class="hot',''))        num0 = num0 + 1        name = verinfo[0]        link = verinfo[1].replace('class="hot','')        ws.cell(row=num0, column=1).value = name        ws.cell(row=num0, column=2).value = link    wb.save('安居客2' + '.xlsx')    print('爬取成功')html = gethtml()parseHotBook(html)

当然,文本存储还有一些瑕疵,因为用的是正则表达式,并没有进行很严格的匹配

贴上爬取图片:

安居客爬取图片

正确的数据 650条左右,因为问了一下给需求的小姐姐,说是可以,所以就这样子处理了。

代码就是上面那些,以后有同样入门的一块学习的小伙伴或者需要帮忙爬虫的,可以私信我,我可以试着去爬一下,因为自己也是自学3个月左右。代码有放到GitHub上了

阅读全文
0 0
原创粉丝点击