python爬虫经典实例(二)

在前一篇博客中,我们介绍了五个实用的爬虫示例,分别用于新闻文章、图片、电影信息、社交媒体和股票数据的采集。本文将继续探索爬虫的奇妙世界,为你带来五个全新的示例,每个示例都有其独特的用途和功能。

1. Wikipedia数据采集

爬虫不仅可以用于商业用途,还可以用于教育和学术研究。让我们以采集维基百科页面为例,获取特定主题的摘要信息。

 
 
import requests
from bs4 import BeautifulSoup

url = 'https://en.wikipedia.org/wiki/Web_scraping'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 提取页面的第一个段落
first_paragraph = soup.find('p').text
print(first_paragraph)

这段代码将抓取维基百科上关于“Web scraping”主题的第一个段落,并将其打印出来。这个示例展示了如何从维基百科等知识源中提取有用的信息。

2. 天气数据爬虫

如果你想获取实时的天气信息,可以使用爬虫从气象网站上获取数据。下面是一个示例,使用Python的requests库:

 
 
import requests

city = 'New_York'
url = f'https://www.example-weather-site.com/weather/{city}'
response = requests.get(url)

# 解析天气数据
data = response.json()
temperature = data['temperature']
humidity = data['humidity']

print(f'Temperature in {city}: {temperature}°C')
print(f'Humidity in {city}: {humidity}%')

这段代码将从指定城市的气象网站上获取温度和湿度数据,并将其打印出来。

3. 招聘信息爬虫

如果你正在寻找工作,可以使用爬虫来收集招聘信息。以下是一个示例,使用Python的requestsBeautifulSoup

 
 
import requests
from bs4 import BeautifulSoup

url = 'https://www.example-job-site.com/jobs'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 找到招聘信息
jobs = soup.find_all('div', class_='job')
for job in jobs:
    title = job.find('h2').text
    company = job.find('span', class_='company').text
    location = job.find('span', class_='location').text
    print(f'Title: {title}')
    print(f'Company: {company}')
    print(f'Location: {location}')

这段代码将从招聘网站上提取职位标题、公司名称和工作地点等信息,帮助你找到心仪的工作机会。

扫描二维码关注公众号,回复: 16703767 查看本文章

4. 电子书爬虫

如果你热衷于阅读,可以使用爬虫来获取电子书。以下是一个示例,使用Python的requests库:

 
 
import requests

book_url = 'https://www.example-ebook-site.com/book/12345'
response = requests.get(book_url)

# 保存电子书到本地
with open('my_ebook.pdf', 'wb') as ebook_file:
    ebook_file.write(response.content)

print('Ebook downloaded successfully!')

这段代码将从指定的电子书网站上下载电子书,并保存到本地以供阅读。

5. 艺术品信息爬虫

如果你是一位艺术爱好者,可以使用爬虫来获取艺术品信息,例如画作、艺术家介绍等。以下是一个示例,使用Python的requestsBeautifulSoup

 
 
import requests
from bs4 import BeautifulSoup

url = 'https://www.example-art-site.com/artworks'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 提取艺术品信息
artworks = soup.find_all('div', class_='artwork')
for artwork in artworks:
    title = artwork.find('h2').text
    artist = artwork.find('span', class_='artist').text
    year = artwork.find('span', class_='year').text
    print(f'Title: {title}')
    print(f'Artist: {artist}')
    print(f'Year: {year}')

这段代码将从艺术品网站上提取艺术品的标题、艺术家和创作年份等信息,帮助你了解更多艺术作品。

结论

以上是五个独特的爬虫示例,展示了爬虫技术的多样性和灵活性。无论你是学者、工程师、艺术爱好者还是求职者,爬虫都可以帮助你获取所需的信息。当然,在实际使用中,务必遵守网站的规定和法律法规,确保爬虫活动的合法性和道德性。爬虫技术的应用范围广泛,只要你有创意,就能发挥无限潜力。希望这些示例能激发你的灵感,让你更好地利用爬虫技术。

猜你喜欢

转载自blog.csdn.net/qq_72290695/article/details/132892288