用python写一段爬虫
时间: 2023-09-30 18:12:35 浏览: 41
以下是用Python写的一个简单的爬虫示例,它可以从一个网站上获取新闻标题和链接:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://news.baidu.com/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
news_list = soup.find_all('a', {'class': 'news-title'})
for news in news_list:
title = news.get_text()
link = news.get('href')
print(title, link)
```
这个爬虫首先使用requests库获取网站的HTML代码,然后使用BeautifulSoup库解析HTML,找到所有类名为“news-title”的链接元素,并从中提取新闻标题和链接。最后,它将这些信息打印到控制台上。
相关问题
使用python写一段爬虫
当然可以!以下是一个简单的Python爬虫示例,使用了第三方库 `requests` 和 `beautifulsoup4`:
```python
import requests
from bs4 import BeautifulSoup
# 发送GET请求获取网页内容
url = 'https://www.example.com'
response = requests.get(url)
html_content = response.text
# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(html_content, 'html.parser')
# 提取需要的信息
title = soup.title.text
links = soup.find_all('a')
# 打印结果
print('网页标题:', title)
print('所有链接:')
for link in links:
print(link['href'])
```
以上示例会爬取 `https://www.example.com` 网页的标题和所有链接,并将结果打印出来。你可以根据需要修改代码来适应不同的爬取任务。记得在使用前安装 `requests` 和 `beautifulsoup4` 库。
用python写一段爬虫代码
好的。下面是用 Python 编写的爬虫代码的示例:
```
import requests
from bs4 import BeautifulSoup
def crawl(url):
# 首先,我们使用 requests 库发送一个 HTTP GET 请求,获取网页内容
response = requests.get(url)
# 然后,使用 BeautifulSoup 库解析网页内容,方便我们提取信息
soup = BeautifulSoup(response.text, 'html.parser')
# 你可以使用 soup 对象的各种方法来提取网页内容,比如使用 find_all() 方法来查找网页中的所有链接
links = soup.find_all('a')
for link in links:
print(link.text, link['href'])
# 调用 crawl() 函数爬取网页内容
crawl('http://example.com')
```
在这段代码中,我们使用了两个库:
- requests:这是一个用于发送 HTTP 请求的库,我们使用它来获取网页内容。
- BeautifulSoup:这是一个用于解析 HTML 和 XML 文档的库,我们使用它来解析网页内容,并提取信息。
在这段代码中,我们首先使用 requests 库发送一个 HTTP GET 请求,然后使用 BeautifulSoup 库解析网页内容,最后使用 find_all() 方法来提取链接。这只是爬虫的一个简单示例,你可以根据自己的需要来编写更复杂的爬虫代码。