这里提供一份简单的Python爬虫代码,用于爬取某个网站上的新闻标题和链接: ```python import requests from bs4 import BeautifulSoup # 设置请求头,模拟浏览器访问 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # 目标网站的URL url = 'https://www.example.com/news' # 发送请求并获取响应 response = requests.get(url, headers=headers) # 使用BeautifulSoup解析HTML soup = BeautifulSoup(response.content, 'html.parser') # 查找新闻标题和链接 news_list = soup.find_all('a', class_='news-title') # 打印结果 for news in news_list: title = news.text.strip() link = news['href'] print(f'{title}: {link}') ``` 这份代码使用了requests库发送HTTP请求,并使用BeautifulSoup库解析HTML。在解析完成后,使用find_all()方法查找新闻标题和链接,并打印结果。 当然,这只是一个简单的示例,实际的爬虫可能需要更复杂的逻辑和处理方式。同时,需要注意的是,爬虫的使用需要遵守网站的规定和法律法规,避免对网站造成过大的负担和损失。
适合初学者的python爬虫代码实现
猜你喜欢
转载自blog.csdn.net/worldkingpan/article/details/129736923
今日推荐
周排行