通过find_elements_by_css_selector方法获取元素

前言

之前有个同学询问我是否能够爬取知乎的全部回答,当初只会Scrapy无法实现下拉的数据全部加载。后来在意外中接触了selenium的自动化测试,看出了selenium的模拟能力的强大,而昨天有个同学问我能否爬取中国工商银行远程银行的精彩回答,我说可以试试。

思路

selenium模拟下拉直至底部
然后通过selenium获取数据集合
通过pandas写入excel
selenium模拟下拉直至底部

此处全靠一位大佬的博客点拨,实在不好意思的是,selenium就看了下常用的api,实在不懂如何判断是否加载完毕,而该博客代码的原理也好理解,通过不断下拉判断与上一次高度进行对比,知道前端页面的滚动高度属性就懂了,当然思想最重要。
见代码:

#将滚动条移动到页面的底部
all_window_height = [] # 创建一个列表,用于记录每一次拖动滚动条后页面的最大高度
all_window_height.append(self.driver.execute_script(“return document.body.scrollHeight;”)) #当前页面的最大高度加入列表
while True:
self.driver.execute_script(“scroll(0,100000)”) # 执行拖动滚动条操作
time.sleep(3)
check_height = self.driver.execute_script(“return document.body.scrollHeight;”)
if check_height == all_window_height[-1]: #判断拖动滚动条后的最大高度与上一次的最大高度的大小,相等表明到了最底部
print(“我已下拉完毕”)
break
else:
all_window_height.append(check_height) #如果不想等,将当前页面最大高度加入列表。
print(“我正在下拉”)
1
2
3
4
5
6
7
8
9
10
11
12
13
然后通过selenium获取数据集合

通过find_elements_by_css_selector方法获取元素对象列表,然后通过遍历列表获取单个对象,通过对象的text属性获取数据。
代码与"通过pandas写入excel"代码想结合。

通过pandas写入excel

example.xlsx

批量将数据依次写入excel,此处个人知道有两种写法,推荐后者。
写法一:

problem = cls.driver.find_elements_by_css_selector(“li h2.item-title a”)
data = pd.read_excel(‘example.xlsx’, sheet_name = ‘Sheet1’)
problemtext = []
for i in problem:
problemtext .append(i.text)
replytext = []
reply = cls.driver.find_elements_by_css_selector(“div.item-right p”)
for j in reply:
replytext.append(j.text)
data.loc[row,‘答案’] = j.text
data[‘问题’] = problemtext
data[‘答案’] = replytext

DataFrame(data).to_excel(‘test.xlsx’, sheet_name=‘Sheet1’)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
写法二:

problem = cls.driver.find_elements_by_css_selector(“li h2.item-title a”)
data = pd.read_excel(‘example.xlsx’, sheet_name = ‘Sheet1’)
row = 1
for i in problem:
data.loc[row,‘问题’] = i.text
row += 1
row = 1
reply = cls.driver.find_elements_by_css_selector(“div.item-right p”)
for j in reply:
data.loc[row,‘答案’] = j.text
row += 1

DataFrame(data).to_excel(‘test.xlsx’, sheet_name=‘Sheet1’)
1
2
3
4
5
6
7
8
9
10
11
12
13
完整代码

import pandas as pd
from pandas import DataFrame
import unittest
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait

class autoLogin(unittest.TestCase):

URL = 'http://zhidao.baidu.com/business/profile?id=87701'


@classmethod
def setUpClass(cls):
	cls.driver = webdriver.Firefox()
	cls.driver.implicitly_wait(20)
	cls.driver.maximize_window()

	

def test_search_by_selenium(self):
	self.driver.get(self.URL)
	self.driver.title
	time.sleep(1)
	#将滚动条移动到页面的底部
	all_window_height =  []
	all_window_height.append(self.driver.execute_script("return document.body.scrollHeight;"))
	while True:
		self.driver.execute_script("scroll(0,100000)") 
		time.sleep(3)
		check_height = self.driver.execute_script("return document.body.scrollHeight;")
		if check_height == all_window_height[-1]:  
			print("我已下拉完毕")
			break
		else:
			all_window_height.append(check_height) 
			print("我正在下拉")
			https://www.ximalaya.com/yinyue/25370904/

https://www.ximalaya.com/yinyue/25370895/
https://www.ximalaya.com/yinyue/25370890/
https://www.ximalaya.com/yinyue/25370883/
https://www.ximalaya.com/yinyue/25370872/
https://www.ximalaya.com/yinyue/25370877/
https://www.ximalaya.com/yinyue/25370860/
https://www.ximalaya.com/yinyue/25370848/
https://www.ximalaya.com/yinyue/25370853/
https://www.ximalaya.com/yinyue/25370843/
https://www.ximalaya.com/yinyue/25370829/
https://www.ximalaya.com/yinyue/25370823/
https://www.ximalaya.com/yinyue/25370820/
https://www.ximalaya.com/yinyue/25370787/
https://www.ximalaya.com/yinyue/25370817/
https://www.ximalaya.com/yinyue/25370777/
https://www.ximalaya.com/yinyue/25370772/
https://www.ximalaya.com/yinyue/25370767/
https://www.ximalaya.com/yinyue/25370724/
https://www.ximalaya.com/yinyue/25370719/
https://www.ximalaya.com/yinyue/25370715/
https://www.ximalaya.com/yinyue/25370707/
https://www.ximalaya.com/yinyue/25370702/
https://www.ximalaya.com/yinyue/25376302/
https://www.ximalaya.com/yinyue/25376297/
@classmethod
def tearDownClass(cls):
html=cls.driver.page_source
problem = cls.driver.find_elements_by_css_selector(“li h2.item-title a”)
data = pd.read_excel(‘example.xlsx’, sheet_name = ‘Sheet1’)
row = 1
for i in problem:
data.loc[row,‘问题’] = i.text
row += 1
row = 1
reply = cls.driver.find_elements_by_css_selector(“div.item-right p”)
for j in reply:
data.loc[row,‘答案’] = j.text
row += 1

	DataFrame(data).to_excel('test.xlsx', sheet_name='Sheet1')

	#保存成网页
	with open("index.html", "wb") as f:
		f.write(html.encode())
	f.close()
	cls.driver.quit()

if name == ‘main’:
unittest.main(verbosity=2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
展示

text.xlsx

总结

在使用Scrapy爬虫时,可以通过selenium来执行网页中的一些js脚本,但是如何将二者结合起来,以及各种框架之间的灵活运用,都将是我需要面对的。

作者:thginWalker
来源:CSDN
原文:https://blog.csdn.net/XZ2585458279/article/details/94761652
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值