python爬虫案例代码
时间: 2023-10-04 21:06:39 浏览: 67
当然,我可以为您提供一个简单的Python爬虫案例代码。以下是一个爬取网页标题的示例:
```python
import requests
from bs4 import BeautifulSoup
# 要爬取的网页链接
url = "https://example.com"
# 发送请求并获取页面内容
response = requests.get(url)
# 使用BeautifulSoup解析页面内容
soup = BeautifulSoup(response.text, "html.parser")
# 提取网页标题
title = soup.title.text
# 打印网页标题
print("网页标题:", title)
```
此代码使用了`requests`库来发送HTTP请求,并使用`BeautifulSoup`库解析HTML内容。它发送GET请求到指定的URL,获取页面内容,然后使用BeautifulSoup解析页面,并从中提取出标题信息。
请注意,这只是一个简单的示例,实际的爬虫代码可能会更复杂,具体取决于您要爬取的网站和需要提取的数据。爬虫行为应符合法律和道德规范,请确保您的爬虫代码遵循相关规定。
相关问题
python爬虫案例源代码
以下是一个Python爬虫案例的源代码,可以用于爬取某吧某帖子全部内容:
```python
import requests
import re
# 定义爬取函数
def crawl_post(url):
response = requests.get(url)
# 使用正则表达式提取帖子内容
pattern = r'<div class="post-content">(.*?)</div>'
content = re.findall(pattern, response.text, re.S)
# 保存内容到文本文件
with open('post_content.txt', 'w', encoding='utf-8') as f:
for c in content:
f.write(c.strip() + '\n')
# 设置帖子的url地址
url = 'http://example.com/post/1'
crawl_post(url)
```
以上代码使用了requests库发送请求,并通过正则表达式提取了帖子的内容。然后将提取的内容保存到文本文件中。你可以根据实际需求修改代码中的url和文件保存路径。这只是一个简单的案例,你还可以根据需要使用其他库和方法来进行更复杂的爬取操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [7个经典python爬虫案例代码分享](https://blog.csdn.net/BlueSocks152/article/details/131145868)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
python简单爬虫案例代码
下面是一个简单的Python爬虫案例代码,它可以爬取指定网页的标题和正文内容:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com' # 指定要爬取的网页URL
response = requests.get(url) # 发送HTTP请求获取网页内容
soup = BeautifulSoup(response.text, 'html.parser') # 解析HTML内容
title = soup.title.string # 获取网页标题
content = soup.body.get_text() # 获取网页正文内容
print('Title:', title)
print('Content:', content)
```
注意:本代码仅供学习参考,请勿用于非法用途。另外,爬取网页时应遵守相关法律法规和网站的使用条款。