python的爬虫基础语法
时间: 2023-11-21 20:56:28 浏览: 36
Python爬虫的基础语法包括以下几个方面:
1.发送HTTP请求:使用requests库发送HTTP请求,获取网页内容。例如:
```python
import requests
response = requests.get('http://www.example.com')
print(response.text)
```
2.解析HTML:使用BeautifulSoup库解析HTML,提取需要的信息。例如:
```python
from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.title)
print(soup.title.string)
print(soup.p['class'])
print(soup.find_all('a'))
```
3.正则表达式:使用re库匹配需要的信息。例如:
```python
import re
pattern = re.compile(r'\d+')
result = pattern.findall('hello 123 world 456')
print(result)
```
4.存储数据:使用文件操作或数据库操作存储获取到的数据。例如:
```python
import csv
with open('data.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Name', 'Age'])
writer.writerow(['Alice', '18'])
writer.writerow(['Bob', '20'])
```