失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python3 [爬虫实战] selenium + requests 爬取安居客

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

时间:2023-10-11 20:44:15

相关推荐

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

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

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

我们爬取的网站:/sy-city.html

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

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

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

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

http://xudailong_blog/

4 现在贴上代码片段:

# -*- coding: utf-8 -*-# @Time : /9/19 21:36# @Author : 蛇崽# @Email : 17193337679@# @File : anjuke.py 安居客房产网import requestsimport refrom bs4 import BeautifulSoupimport csvimport timeimport threadingfrom lxml import etreefrom selenium import webdriverfrom openpyxl import Workbooknum0 = 1 # 用来计数,计算爬取的书一共有多少本baseurl = '/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_sourcereturn htmldef saveinfos(authorother):global num0nums = 0for ver_info in authorother:num0 = num0 + 1ws.cell(row=num0, column=1).value = ver_info[0]ws.cell(row=num0, column=2).value = ver_info[1]nums += 1print('爬取成功 ' + 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 = pile(regAuthor)authorother = re.findall(reg_author, html)global num0nums = 0for info in authorother:verinfo = info.split('">')print(verinfo[0],verinfo[1].replace('class="hot',''))num0 = num0 + 1name = verinfo[0]link = verinfo[1].replace('class="hot','')ws.cell(row=num0, column=1).value = namews.cell(row=num0, column=2).value = linkwb.save('安居客2' + '.xlsx')print('爬取成功')html = gethtml()parseHotBook(html)

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

贴上爬取图片:

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

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

如果觉得《python3 [爬虫实战] selenium + requests 爬取安居客》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。