Python爬虫可以用于爬取各种类型的数据,但通常情况下,选择爬取的数据类型取决于你的需求和目标网站的结构。以下是一些简单的Python爬虫示例,你可以根据自己的需求进行修改:
1. 爬取百度百科页面:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://baike.baidu.com/item/Python' 示例网址
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
提取标题
titles = soup.find_all('h1')
for title in titles:
print(title.text)
2. 爬取网页上的图片:
```python
import urllib
import re
def getHtmlContent(url):
page = urllib.urlopen(url)
return page.read()
def getJPGs(html):
jpgReg = re.compile(r']+src="([^"]+)"')
return jpgReg.findall(html)
url = 'https://example.com' 示例网址
html = getHtmlContent(url)
jpg_urls = getJPGs(html)
for jpg_url in jpg_urls:
print(jpg_url)
3. 使用Requests和BeautifulSoup爬取一个简单的网页:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com' 示例网址
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
提取所需信息,例如提取所有的标题
titles = soup.find_all('h1')
for title in titles:
print(title.text)
else:
print('请求失败,状态码:', response.status_code)
这些示例展示了如何使用Python的`requests`库发送网络请求,并使用`BeautifulSoup`库解析HTML内容。你可以根据自己的需求修改这些代码,比如更改目标网址、提取不同的数据等。
请注意,在进行网络爬取时,要遵守目标网站的`robots.txt`文件规定,尊重网站的版权声明,以及考虑到网站的反爬虫机制。