写一个Python的爬虫代码
时间: 2023-03-03 10:07:50 浏览: 9
好的,以下是一个简单的Python爬虫代码示例,它可以爬取指定网站的网页内容:
```python
import requests
from bs4 import BeautifulSoup
# 要爬取的目标网站URL
url = 'https://example.com'
# 发起GET请求
response = requests.get(url)
# 解析HTML内容
soup = BeautifulSoup(response.text, 'html.parser')
# 打印网页标题
print(soup.title.text)
# 打印所有链接的href属性值
for link in soup.find_all('a'):
print(link.get('href'))
```
这个爬虫代码示例使用了`requests`库来发起HTTP请求,并使用`BeautifulSoup`库来解析HTML内容。你可以根据自己的需要修改和扩展这个示例,以实现更复杂的爬虫功能。需要注意的是,爬取网站时请遵守相关法律法规和网站的使用条款。
相关问题
写一个Python爬虫代码
好的,这是一个简单的Python爬虫代码,用于爬取网页内容:
```
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print(soup.prettify())
```
这段代码使用了`requests`库来发送HTTP请求并获取网页内容,并使用`BeautifulSoup`库来解析HTML文档,最后通过`prettify()`方法格式化输出网页内容。
请注意,您需要在执行此代码前先安装`requests`和`beautifulsoup4`库。
写一个python爬虫代码样例
当然可以!以下是一个简单的Python爬虫代码样例,用于从网页中获取文章内容:
```python
import requests
from bs4 import BeautifulSoup
def get_web_content(url):
# 发送HTTP GET请求获取网页内容
response = requests.get(url)
if response.status_code == 200:
# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(response.content, 'html.parser')
# 获取文章标题
title = soup.find('h1').text.strip()
# 获取文章内容
content = soup.find('div', class_='article-content').text.strip()
return title, content
else:
return None
# 指定要爬取的网页URL
url = 'https://www.example.com/article'
# 调用函数获取网页内容
result = get_web_content(url)
if result:
title, content = result
print(f"文章标题:{title}")
print(f"文章内容:{content}")
else:
print("获取网页内容失败")
```
以上代码使用了`requests`库发送HTTP请求,以及`BeautifulSoup`库解析网页内容。你可以根据需要修改代码中的URL和解析规则以适应不同的网页。