import time import openpyxl from selenium import webdriver from bs4 import BeautifulSoup # 设置请求头,模拟真实浏览器访问 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36', } # 使用Selenium启动浏览器 driver = webdriver.Chrome() data = [] counter = 1 # 序列号计数器 # 打开网页 for i in range(1,6): url = 'https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&psort=3&wq=%E6%89%8B%E6%9C%BA&psort=3&pvid=0faa3ec65d444d68a66161cdf464d451&psort=3&page={}&s=61&click=0'.format( (i * 2) - 1) driver.get(url) # 模拟滚动页面,以触发异步请求加载更多商品信息 driver.execute_script('window.scrollTo(0, document.body.scrollHeight);') time.sleep(2) # 获取完整页面内容 html = driver.page_source # 解析网页内容,提取商品名称和价格信息 soup = BeautifulSoup(html, 'html.parser') products = soup.select('.gl-item') for product in products: product_id = product['data-sku'] # 提取产品ID name = product.select('.p-name em')[0].text.strip() product_url = 'https:' + product.select('.p-name a')[0]['href'] # 修改产品URL price = product.select('.p-price strong i')[0].text.strip() data.append([counter, product_id, name, product_url, price]) # 将产品数据添加到列表中 counter += 1 # 每个产品的增量计数器 # 关闭浏览器 driver.quit() # 创建Excel文件并保存数据 wb = openpyxl.Workbook() ws = wb.active ws.append(['top', '商品ID', '商品名称', '商品链接', '价格']) # 添加已修改列顺序的标题行 for item in data: ws.append(item) wb.save('jd_top300.xlsx') print("数据已保存到jd_top300.xlsx文件。")
时间: 2024-02-03 17:02:49 浏览: 292
这是一个爬取京东手机商品信息的Python脚本,使用了Selenium和BeautifulSoup库。脚本会自动打开Chrome浏览器,模拟滚动页面,获取商品信息,然后将数据保存到Excel文件中。具体解释如下:
1. 导入必要的库:time、openpyxl、selenium和BeautifulSoup。
2. 设置请求头,模拟真实浏览器访问。
3. 使用Selenium启动Chrome浏览器。
4. 定义一个空列表data,用于存储获取的商品数据。
5. 定义一个计数器counter,用于给每个商品编号。
6. 循环遍历5页的商品列表,每页包含60个商品。
7. 访问每个页面,并模拟滚动页面,以触发异步请求加载更多商品信息。
8. 获取完整页面内容。
9. 使用BeautifulSoup解析网页内容,提取商品名称和价格信息。
10. 将商品数据添加到列表data中,并给每个商品编号。
11. 关闭浏览器。
12. 创建一个Excel文件,并将商品数据保存到文件中。
13. 输出保存数据的文件名。
注意:爬取商品信息需要遵守相关法律法规和京东网站的规定。
相关问题
from selenium import webdriver from selenium.webdriver.chrome.options import Options from bs4 import BeautifulSoup import time # 目标网站的 URL url = 'http://example.com/rank/list' # Chrome 浏览器配置 chrome_options = Options() chrome_options.add_argument('--disable-extensions') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-dev-shm-usage') # 启动 Chrome 浏览器 browser = webdriver.Chrome(options=chrome_options) # 发起第一页的请求并解析 HTML 标签 browser.get(url) time.sleep(3) # 等待 3 秒钟,等待 AJAX 加载完成 soup = BeautifulSoup(browser.page_source, 'html.parser') total_pages = soup.select('.ant-pagination-item:not(.ant-pagination-next):not(.ant-pagination-prev)')[-1]['title'] current_page = soup.select_one('.ant-pagination-item-active').text rank_list = parse_page(soup) # 发起所有页码的请求,并将结果存入列表中 for page in range(2, int(total_pages) + 1): if str(page) != current_page: # 模拟在浏览器中翻页操作 browser.execute_script(f'window.antDesignPro.current.delete("/rank/list?page={int(current_page)}")') # 删除当前页的数据 browser.execute_script(f'window.antDesignPro.current.jump("/rank/list?page={page}")') # 跳转到需要打开的页码 time.sleep(3) # 等待 3 秒钟,等待 AJAX 加载完成 soup = BeautifulSoup(browser.page_source, 'html.parser') page_data = parse_page(soup) rank_list += page_data current_page = page # 将所有分页数据合并成一个完整的 DataFrame 对象 all_data = merge_data(rank_list) # 关闭浏览器窗口 browser.quit() # 打印输出结果 print(all_data),注意:目标网站采用了 AJAX 或者 JavaScript 技术来进行分页加载数据,因此翻页时并没有刷新整个页面,也无法从html文本获得第一页以后的排名帮我修改代码,要求用到request和beautifulsoup等库,
好的,以下是修改后的代码,使用了 requests 和 BeautifulSoup 库来发送请求和解析 HTML 标签:
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
def get_rank_list(url):
# 发起第一页的请求并解析 HTML 标签
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
total_pages = soup.select('.ant-pagination-item:not(.ant-pagination-next):not(.ant-pagination-prev)')[-1]['title']
current_page = soup.select_one('.ant-pagination-item-active').text
rank_list = parse_page(soup)
# 发起所有页码的请求,并将结果存入列表中
for page in range(2, int(total_pages) + 1):
if str(page) != current_page:
# 模拟在浏览器中翻页操作
headers = {
'Referer': url,
'X-Requested-With': 'XMLHttpRequest'
}
res = requests.delete(url, headers=headers, params={'page': int(current_page)}) # 删除当前页的数据
res = requests.get(url, headers=headers, params={'page': page}) # 跳转到需要打开的页码
soup = BeautifulSoup(res.text, 'html.parser')
page_data = parse_page(soup)
rank_list += page_data
current_page = page
# 等待 3 秒钟,等待 AJAX 加载完成
time.sleep(3)
# 将所有分页数据合并成一个完整的 DataFrame 对象
all_data = merge_data(rank_list)
return all_data
def parse_page(soup):
rank_list = []
for tr in soup.select('tbody tr'):
rank = tr.select_one('.rank').text.strip() # 排名
name = tr.select_one('.name').text.strip() # 名称
score = tr.select_one('.score').text.strip() # 得分
rank_list.append([rank, name, score])
return rank_list
def merge_data(rank_list):
df = pd.DataFrame(rank_list, columns=['rank', 'name', 'score'])
return df
if __name__ == '__main__':
url = 'http://example.com/rank/list'
all_data = get_rank_list(url)
print(all_data)
```
注意:目标网站采用了 AJAX 或者 JavaScript 技术来进行分页加载数据,因此需要在请求头中添加 `X-Requested-With` 和 `Referer` 参数,以模拟浏览器发送请求。此外,还需要等待 AJAX 加载完成后再解析 HTML 标签,可以使用 `time.sleep()` 函数来实现。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)