Python使用urllib和bs4库爬虫步骤
时间: 2024-01-02 16:14:56 浏览: 36
以下是使用urllib和bs4库进行爬虫的基本步骤:
1. 导入必要的库:
```python
from urllib.request import urlopen
from bs4 import BeautifulSoup
```
2. 打开目标网页:
```python
html = urlopen("http://www.example.com")
```
3. 使用BeautifulSoup解析html:
```python
soup = BeautifulSoup(html, 'html.parser')
```
4. 找到需要提取的信息:
```python
# 找到所有的a标签
links = soup.find_all('a')
# 找到第一个h1标签
heading = soup.find('h1')
```
5. 提取信息:
```python
# 提取第一个a标签的href属性值
link = links[0].get('href')
# 提取第一个h1标签的文本内容
title = heading.text
```
完整代码示例:
```python
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.example.com")
soup = BeautifulSoup(html, 'html.parser')
# 找到所有的a标签
links = soup.find_all('a')
# 找到第一个h1标签
heading = soup.find('h1')
# 提取第一个a标签的href属性值
link = links[0].get('href')
# 提取第一个h1标签的文本内容
title = heading.text
print("Link:", link)
print("Title:", title)
```