python爬虫案例网页数据
时间: 2025-03-03 09:43:59 浏览: 42
### Python 爬虫抓取网页数据案例
#### 使用 `requests` 和 `BeautifulSoup` 进行简单的网页抓取
为了展示如何利用Python进行基本的数据抓取,下面是一个使用`requests`库发送HTTP请求并用`BeautifulSoup`解析HTML文档的例子[^3]。
```python
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0'}
req = requests.get(url=url, headers=headers)
soup = BeautifulSoup(req.text, "lxml")
for link in soup.find_all('a'):
print(link.get('href'))
```
此段代码展示了怎样设置自定义头部信息来伪装成浏览器发起GET请求,并通过遍历所有的超链接标签提取URL地址。
#### 处理POST请求提交表单数据
当目标页面需要用户输入某些参数才能显示所需内容时,则可能需要用到POST方法。这里给出一个例子说明如何构建带有data字段的POST请求[^2]:
```python
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post("http://httpbin.org/post", data=payload)
print(response.status_code)
print(response.json())
```
这段脚本向指定服务器发送了一个包含键值对作为负载体的POST请求,并打印返回的状态码以及JSON格式的结果。
#### 将爬取到的信息存储为Excel表格
对于希望把收集来的资料整理成结构化形式的情况而言,可以借助pandas库轻松完成这项工作[^4]。以下是将多个页面上的条目汇总至单一电子表格内的示范程序片段:
```python
import pandas as pd
data_list = []
base_url = "http://www.example.com/page={}"
for i in range(1, 6): # 假设有五页可翻阅
page_content = requests.get(base_url.format(i)).content
parsed_html = BeautifulSoup(page_content, features="html.parser")
items = parsed_html.select(".item-class") # 替换成实际的目标元素CSS选择器
for item in items:
title = item.h2.a.string.strip()
price = float(item.span['data-price'])
row_dict = {"Title": title,
"Price": price}
data_list.append(row_dict)
df = pd.DataFrame(data_list)
writer = pd.ExcelWriter('output.xlsx')
df.to_excel(writer, index=False)
writer.save()
```
上述实例中,先循环读入各分页的内容,再逐一分析每一页中的商品记录;最后把这些记录转换成DataFrame对象以便于后续操作,比如写入Excel文件之中。
阅读全文
相关推荐
















