python爬取中国欧盟商会最新新闻

本文介绍了一个使用Python的requests库和BeautifulSoup库进行网页数据抓取的实例,目标网站为欧洲商会的英文新闻页面。通过发送HTTP请求获取网页内容,再利用BeautifulSoup解析HTML并选择特定元素,实现了新闻标题、类别和链接的有效抓取。
from bs4 import BeautifulSoup
import requests
import time

t0 = time.perf_counter()
url = "https://www.europeanchamber.com.cn/en/press-releases"
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'
}

html = requests.get(url,headers = headers).content

t1 = time.perf_counter()

soup = BeautifulSoup(html, "lxml").select(".panel-default")


i=0

t2 = time.perf_counter()

for sp in soup:
    i = i +1
    print(str(i),  sp.select(".chapter-category")[0].text.strip()[:10], sp.select("h3 a")[0].text)
    print("https://www.europeanchamber.com.cn" + sp.select("h3 a")[0].attrs['href'])

t3 = time.perf_counter()

#各个步骤所耗时间
print("read:", t1-t0)
print("soup:", t2-t1)
print("print:", t3-t2)

 

Python爬取滚动新闻通常涉及到动态网页抓取,因为许多网站会通过JavaScript或其他前端技术来加载更多内容。你可以使用Selenium库配合ChromeDriver等浏览器驱动程序,模拟用户操作来实现滚动加载内容。以下是基本步骤: 1. 安装必要的库: ```bash pip install selenium requests beautifulsoup4 ``` 2. 导入所需模块并初始化浏览器: ```python from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() # 如果是Firefox,则替换为webdriver.Firefox() driver.get('目标新闻网站URL') ``` 3. 模拟滚动: ```python last_height = driver.execute_script("return document.body.scrollHeight") # 获取初始页面高度 while True: driver.execute_script(f"window.scrollTo(0, {last_height});") # 滚动到底部 time.sleep(2) # 为了防止过于频繁请求导致封IP,设置适当延迟 new_height = driver.execute_script("return document.body.scrollHeight") # 更新新的页面高度 if new_height == last_height: # 如果没有更多内容加载,跳出循环 break last_height = new_height ``` 4. 提取数据: 使用BeautifulSoup解析HTML,提取你需要的新闻标题、链接、时间等信息。 5. 结束会话并保存结果: ```python news_data = ... # 这里处理获取到的数据 driver.quit() ``` 注意,遵守网站的Robots协议,并尊重网站的反爬虫策略。同时,频繁的爬取可能会对服务器造成压力,因此请合理设置请求间隔和代理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值