|
发表于 2023-12-18 17:12:20
|
显示全部楼层
当然!下面是经过整理的代码示例:
- import requests
- from bs4 import BeautifulSoup
- def get_headlines():
- # 新浪新闻首页URL
- url = "https://news.sina.com.cn/"
- try:
- # 发送GET请求获取网页内容
- response = requests.get(url)
- # 设置编码方式
- response.encoding = 'utf-8'
- # 获取网页内容
- html = response.text
- # 使用BeautifulSoup解析网页内容
- soup = BeautifulSoup(html, 'html.parser')
- # 获取新闻头条部分的HTML元素
- headlines_div = soup.select('.blk_02')
- headlines = []
- if headlines_div:
- for item in headlines_div[0].select('a'):
- title = item.text.strip()
- if title:
- # 获取新闻详情页面URL
- news_url = item['href']
- # 获取新闻详情页面的内容
- news_content = get_news_content(news_url)
- # 将标题和内容存储为字典
- news = {'title': title, 'content': news_content}
- headlines.append(news)
- return headlines
- except requests.exceptions.RequestException as e:
- print("网络请求出错:", e)
- except Exception as e:
- print("解析页面出错:", e)
- def get_news_content(url):
- try:
- # 发送GET请求获取新闻详情页面内容
- response = requests.get(url)
- response.encoding = 'utf-8'
- html = response.text
- # 使用BeautifulSoup解析新闻详情页面内容
- soup = BeautifulSoup(html, 'html.parser')
- # 根据实际情况,使用适当的选择器获取新闻内容
- content_div = soup.select('.article')
- if content_div:
- content = content_div[0].text.strip()
- return content
- else:
- return ""
- except requests.exceptions.RequestException as e:
- print("网络请求出错:", e)
- except Exception as e:
- print("解析页面出错:", e)
- if __name__ == '__main__':
- headlines = get_headlines()
- for i, news in enumerate(headlines, 1):
- print(f"新闻{i}:{news['title']}")
- print(f"内容:{news['content']}")
- print()
复制代码
在这个整理后的代码中,主要进行了以下优化:
1. 对于`headlines_div`和`content_div`的判断,使用了索引`[0]`来确保只取第一个符合条件的元素。
2. 在获取新闻详情页面URL时,通过`item['href']`来直接获取URL属性值。
3. 在获取新闻内容时,加入了对`content_div`是否存在的判断,并返回空字符串作为默认值。
4. 打印新闻标题和内容时,使用了字典中相应的键来访问对应的值。
希望这次整理的代码能更好地解决问题!如果还有其他疑问,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|