pycharm爬虫代码
时间: 2023-10-21 14:30:03 浏览: 36
以下是一个简单的 Python 爬虫代码,使用 PyCharm 编写:
```python
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com"
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.content, "html.parser")
# 打印网页标题
print(soup.title.text)
# 打印所有链接
for link in soup.find_all("a"):
print(link.get("href"))
else:
print("网页请求失败")
```
在这个示例中,我们使用 requests 库发送 HTTP 请求,并使用 BeautifulSoup 库解析 HTML 响应。我们首先创建一个 URL 变量,然后使用 requests.get() 方法发送 GET 请求。如果响应状态码为 200,我们将使用 BeautifulSoup 解析 HTML 响应。我们打印了网页标题和所有链接。如果响应状态码不为 200,我们将打印一条错误消息。
相关问题
pycharm爬虫代码案例
以下是一个使用 PyCharm 编写的简单爬虫代码案例:
```python
import requests
from bs4 import BeautifulSoup
# 发送 HTTP 请求获取数据
url = 'https://www.example.com'
response = requests.get(url)
# 解析 HTML 数据
soup = BeautifulSoup(response.text, 'html.parser')
links = soup.find_all('a')
# 遍历所有链接并打印
for link in links:
print(link.get('href'))
```
这个代码会向指定的 URL 发送 HTTP 请求,然后使用 BeautifulSoup 库解析 HTML 数据。最后,它会遍历所有的链接并打印它们的地址。在 PyCharm 中运行这个代码非常简单,只需要创建一个 Python 项目,然后将这个代码复制到 main.py 文件中。然后点击运行按钮即可执行代码。
pycharm爬虫代码爬取CSDN
以下是一个使用 requests 和 BeautifulSoup 库爬取 CSDN 首页文章列表的代码示例:
```python
import requests
from bs4 import BeautifulSoup
# 发送请求并获取响应
url = 'https://www.csdn.net/'
response = requests.get(url)
# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 获取文章列表
articles = soup.select('.feedlist_mod > .clearfix > dl')
for article in articles:
title = article.select_one('.title > h2 > a').text.strip()
link = article.select_one('.title > h2 > a')['href']
summary = article.select_one('.summary').text.strip()
print(title)
print(link)
print(summary)
```
请注意,CSDN 的使用协议禁止对网站进行爬取,请遵守相关规定。