import requests from bs4 import BeautifulSoup import csv # 发送HTTP请求获取网页内容 url = "https://item.jd.com/100016034394.html" # 替换为目标商品评价页面的URL response = requests.get(url) html = response.text # 使用BeautifulSoup解析网页内容 soup = BeautifulSoup(html, "html.parser") # 获取所有评价信息 comments = soup.find_all("div", class_="comment-item") # 创建CSV文件并写入数据 filename = "商品评价.csv" with open(filename, "w", encoding="utf-8-sig", newline="") as csvfile: writer = csv.writer(csvfile) writer.writerow(["用户", "评分", "评价内容"]) # 写入表头 # 写入每条评价的数据 for comment in comments: user = comment.find("div", class_="user-info").find("span").text.strip() rating = comment.find("div", class_="comment-star").find("i")["class"][1].split("-")[1] content = comment.find("div", class_="comment-con").find("p").text.strip() writer.writerow([user, rating, content]) print(f"成功爬取并保存为 {filename}") ConnectionError: HTTPSConnectionPool(host='www.jd.com', port=443): Max retries exceeded with url: /?from=pc_item_sd (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000015FCC4912E0>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。'))
时间: 2023-12-05 16:45:20 浏览: 234
这个错误通常是由于连接超时或无法建立与目标网站的连接所致。可以尝试以下解决方案:
1. 检查网络连接:确保你的计算机可以正常访问互联网,并且能够连接到目标网站。你可以尝试使用浏览器访问该网址,以确认是否能够成功打开页面。
2. 增加请求超时时间:在发送请求时,可以指定一个较长的超时时间,以允许更多时间来建立连接。将`requests.get()`函数中的`timeout`参数设置为一个较大的值,例如`timeout=10`,表示等待10秒钟来建立连接。
```python
response = requests.get(url, timeout=10)
```
3. 添加异常处理机制:在发起请求时,可以添加异常处理机制来捕获可能出现的连接错误。这样可以确保程序在遇到连接问题时不会中断,而是继续执行后续操作。
```python
try:
response = requests.get(url, timeout=10)
# 其他代码
except requests.exceptions.RequestException as e:
print("请求异常:", e)
```
4. 使用代理服务器:如果你的网络环境有限制或目标网站对爬虫有限制,可以尝试使用代理服务器来发送请求。通过设置`requests.get()`函数中的`proxies`参数,指定代理服务器的地址和端口。
```python
proxies = {
'http': 'http://proxy.example.com:8080',
'https': 'http://proxy.example.com:8080',
}
response = requests.get(url, proxies=proxies)
```
根据具体情况选择适合的解决方案,以确保能够成功建立连接并爬取目标网页的数据。