一个简单的爬虫demo
时间: 2023-10-03 17:02:16 浏览: 52
当然,这里是一个使用 Python 编写的简单爬虫 demo:
```python
import requests
from bs4 import BeautifulSoup
def crawl(url):
# 请求网页数据
response = requests.get(url)
# 解析 HTML 数据
soup = BeautifulSoup(response.text, "html.parser")
# 提取想要的信息
title = soup.find("h1").text
# 返回结果
return {
"title": title,
}
# 爬取网页
result = crawl("https://www.example.com/")
# 输出结果
print(result)
```
这个爬虫会请求指定的 URL,然后使用 BeautifulSoup 解析 HTML 数据,最后使用 `find()` 方法提取 h1 标签的文本内容。
当然,这只是一个简单的 demo,实际的爬虫可能会更加复杂,比如需要模拟登录、分页爬取、使用代理等。
相关问题
写一个Ubuntu下的爬虫demo
好的,这里是一个基于 Python 和 BeautifulSoup 的简单爬虫 demo,可以在 Ubuntu 下运行:
首先,在终端中安装必要的依赖库:
```
sudo apt-get update
sudo apt-get install python3 python3-pip
pip3 install requests beautifulsoup4
```
然后,创建一个名为 `crawler.py` 的 Python 文件,并在其中编写以下代码:
```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')
links = soup.find_all('a')
for link in links:
href = link.get('href')
if href:
print(href)
else:
print('Error:', response.status_code)
```
在这个 demo 中,我们使用 `requests` 库发送 HTTP 请求并获取网页内容,然后使用 `BeautifulSoup` 库解析 HTML 标签并提取网页中的链接,最后将链接打印到终端中。
保存并运行 `crawler.py` 文件:
```
python3 crawler.py
```
你可以将 `https://www.example.com` 替换成你想要爬取的网站地址,也可以根据具体需求修改代码。
请给出一个python 爬虫代码demo
好的,以下是一个简单的 Python 爬虫代码demo,可以爬取指定网站的文章标题和链接:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头,模拟浏览器访问
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 要爬取的网站链接
url = 'https://www.example.com/'
# 发送 GET 请求,获取网页内容
response = requests.get(url, headers=headers)
# 解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
# 获取所有文章标题和链接
articles = soup.find_all('a', class_='article-title')
# 遍历所有文章,输出标题和链接
for article in articles:
title = article.text.strip()
link = article['href']
print(title, link)
```
注意:在实际使用中,需要根据目标网站的结构和特点,进行相应的修改和调整。同时,需要遵守网站的爬虫规则和协议,避免对目标网站造成不必要的影响和损害。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)