pycharm爬虫代码
时间: 2023-11-01 07:55:44 浏览: 29
以下是一个简单的爬虫代码,可以爬取指定网站的信息:
```python
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com/" # 替换为你要爬取的网站地址
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 获取网页标题
title = soup.title.string
print("网页标题:", title)
# 获取网页中的所有链接
links = []
for link in soup.find_all("a"):
links.append(link.get("href"))
print("网页中的链接:", links)
# 获取网页中的所有图片
imgs = []
for img in soup.find_all("img"):
imgs.append(img.get("src"))
print("网页中的图片:", imgs)
```
代码中使用了 requests 库和 BeautifulSoup 库,需要先安装这两个库。你可以使用以下命令来安装:
```
pip install requests
pip install beautifulsoup4
```
在运行代码之前,需要将 url 替换为你要爬取的网站地址。运行代码后,会输出网页的标题、所有链接和所有图片的地址。
相关问题
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 的使用协议禁止对网站进行爬取,请遵守相关规定。