Python 爬取代码
时间: 2023-08-27 08:12:41 浏览: 54
以下是一个使用Python的requests和BeautifulSoup库进行简单爬取的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 发送GET请求
url = 'https://www.example.com'
response = requests.get(url)
# 解析HTML内容
soup = BeautifulSoup(response.content, 'html.parser')
# 获取网页标题并输出
title = soup.title.string
print('网页标题:', title)
# 获取所有的超链接
links = soup.find_all('a')
for link in links:
href = link.get('href')
print('超链接:', href)
```
在上述代码中,我们首先使用requests库发送一个GET请求,然后使用BeautifulSoup库解析返回的HTML内容。我们可以使用soup对象来查找HTML标签和属性,并获取它们的值。在这个例子中,我们获取了网页标题和所有的超链接。
相关问题
python爬取数据代码
Python爬取数据的代码可以使用第三方库如Requests、BeautifulSoup等来进行网页爬取和解析。
首先,需要安装相应的库,可以通过pip命令来安装:
```
pip install requests
pip install beautifulsoup4
```
然后,导入所需的库:
```python
import requests
from bs4 import BeautifulSoup
```
接下来,可以使用requests库的get方法获取指定网页的内容,并将其存储在一个变量中:
```python
url = 'http://www.example.com'
response = requests.get(url)
html_content = response.text
```
然后,可以使用BeautifulSoup库的解析方法将网页内容转换为BeautifulSoup对象:
```python
soup = BeautifulSoup(html_content, 'html.parser')
```
接下来,可以使用BeautifulSoup的查找和提取方法来获取网页中的特定数据。例如,可以使用find或find_all方法根据HTML标签名和属性来查找特定元素:
```python
# 查找所有的a标签
links = soup.find_all('a')
# 查找class属性为 'title' 的div标签
divs = soup.find_all('div', class_='title')
# 查找id属性为 'content' 的p标签
paragraph = soup.find('p', id='content')
```
最后,可以根据需求对爬取到的数据进行处理和存储,如打印、保存到文件等:
```python
# 打印所有链接的文本内容和链接地址
for link in links:
print(link.text, link['href'])
# 将div标签的文本内容保存到文件
with open('data.txt', 'w', encoding='utf-8') as f:
for div in divs:
f.write(div.text + '\n')
```
以上就是用Python爬取数据的简单示例代码,通过使用第三方库可以更加方便地实现各种网页数据的爬取和处理。
python爬取区划代码
您好,如果您想要Python爬取区划代码,可以使用requests和BeautifulSoup库来解析网页信息。以下是一个简单的爬取国家统计局的行政区划代码的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = "http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2020/index.html"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
provinces = soup.select('.provincetr a')
for province in provinces:
print(province.text)
```
以上代码可以输出国家统计局行政区划代码中所有省份的名称。