用pycharm使用selenium模拟浏览器访问京东,爬取京东网站商品
时间: 2023-12-13 21:06:15 浏览: 82
首先,你需要安装selenium和chromedriver。chromedriver是Chrome浏览器的驱动程序,它可以让你通过代码控制Chrome浏览器。
在安装完selenium和chromedriver之后,你可以按照以下步骤使用selenium模拟浏览器访问京东并爬取商品:
1. 导入必要的库
```python
from selenium import webdriver
import time
```
2. 打开Chrome浏览器,并访问京东网站
```python
browser = webdriver.Chrome()
browser.get('https://www.jd.com/')
```
3. 在搜索框中输入要搜索的商品,并点击搜索按钮
```python
search_box = browser.find_element_by_xpath('//*[@id="key"]')
search_box.send_keys('商品名称')
search_button = browser.find_element_by_xpath('//*[@id="search"]/div/div[2]/button')
search_button.click()
```
4. 等待页面加载完成,并滚动到页面底部,使所有商品都加载出来
```python
time.sleep(5) # 等待5秒钟,让页面加载完成
browser.execute_script('window.scrollTo(0, document.body.scrollHeight)') # 滚动到页面底部,使所有商品都加载出来
```
5. 爬取商品信息
```python
goods = browser.find_elements_by_class_name('gl-item') # 获取商品列表
for good in goods:
title = good.find_element_by_xpath('.//div[@class="p-name"]/a/em') # 获取商品标题
price = good.find_element_by_xpath('.//div[@class="p-price"]/strong/i') # 获取商品价格
print(title.text, price.text)
```
6. 关闭浏览器
```python
browser.quit()
```
完整代码如下:
```python
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get('https://www.jd.com/')
search_box = browser.find_element_by_xpath('//*[@id="key"]')
search_box.send_keys('商品名称')
search_button = browser.find_element_by_xpath('//*[@id="search"]/div/div[2]/button')
search_button.click()
time.sleep(5)
browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
goods = browser.find_elements_by_class_name('gl-item')
for good in goods:
title = good.find_element_by_xpath('.//div[@class="p-name"]/a/em')
price = good.find_element_by_xpath('.//div[@class="p-price"]/strong/i')
print(title.text, price.text)
browser.quit()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)