您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 如何利用Selenium库爬取京东Python书籍一百页存入CSV
## 一、环境准备
首先需要安装必要的Python库:
```python
pip install selenium pandas
同时需下载对应浏览器的WebDriver(如Chrome需下载chromedriver),并将其路径加入系统环境变量。
from selenium import webdriver
from selenium.webdriver.common.by import By
import pandas as pd
import time
driver = webdriver.Chrome()
base_url = "https://search.jd.com/Search?keyword=Python&page={}&s=1&click=0"
京东书籍页面采用动态加载,需模拟滚动操作:
def scroll_page():
for i in range(1, 5):
driver.execute_script(f"window.scrollTo(0, {i*500})")
time.sleep(0.5)
通过XPath定位书籍信息:
def parse_page():
books = []
items = driver.find_elements(By.XPATH, '//div[@id="J_goodsList"]//li[@class="gl-item"]')
for item in items:
title = item.find_element(By.XPATH, './/div[@class="p-name"]/a/em').text
price = item.find_element(By.XPATH, './/div[@class="p-price"]//i').text
books.append([title, price])
return books
all_books = []
for page in range(1, 101): # 爬取100页
driver.get(base_url.format(page))
scroll_page()
all_books.extend(parse_page())
print(f"已完成第{page}页抓取")
time.sleep(2) # 避免触发反爬
使用pandas保存为CSV:
df = pd.DataFrame(all_books, columns=["书名", "价格"])
df.to_csv("jd_python_books.csv", index=False, encoding='utf_8_sig')
driver.quit()
time.sleep(random.uniform(1,3))
options = webdriver.ChromeOptions()
options.add_argument('user-agent=Mozilla/5.0')
完整代码约80行,实际执行需约30-60分钟完成100页抓取。建议在非高峰时段运行,并添加异常处理机制保证稳定性。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。