使用selenium爬取36氪

本文详细介绍了如何利用Python的Selenium库爬取36氪网站的资讯信息,包括进入首页、获取资讯专栏、提取信息以及数据的合并与序列化写入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 代码
  • 代码分析
    (图片在最下面)
from selenium import webdriver

chrome_driver=r"C:\Users\yandi\AppData\Local\Programs\Python\Python37-32\chromedriver.exe"
driver=webdriver.Chrome(executable_path=chrome_driver)
driver.get('https://36kr.com/')
#获取资讯栏
driver.find_element_by_xpath('//*[@id="information"]').click()
#%%获取每一条资讯的信息
typelist,authorlist,titlelist = [],[],[]
i = 1
while(True):
    try:
        type = driver.find_element_by_xpath(
            '//div[@class="information-flow-list"]/div['+str(i)+']//span[@class="kr-flow-bar-motif"]/a').text
        typelist.append(type)

        author = driver.find_element_by_xpath(
            '//div[@class="information-flow-list"]/div['+str(i)+']//a[@class="kr-flow-bar-author"]').text
        authorlist.append(author)

        title = driver.find_element_by_xpath(
            '//div[@class="information-flow-list"]/div['+str(i
### 使用 Selenium 爬取 NBA 网站数据 #### 安装依赖项 为了启动此项目,需安装 Python 3.x 和 Geckodriver(适用于 Firefox 浏览器)。此外,还需安装 `requirements.txt` 中列出的一些 Python 库[^3]。 ```bash pip install selenium pandas requests beautifulsoup4 ``` #### 初始化 WebDriver 创建一个新的 Python 文件并导入必要的模块: ```python from selenium import webdriver import time ``` 初始化 Web 驱动程序实例,并设置隐式等待时间以便加载 JavaScript 渲染的内容: ```python driver = webdriver.Firefox(executable_path='/path/to/geckodriver') driver.implicitly_wait(10) # seconds ``` #### 访问目标 URL 并抓取数据 访问 NBA 的官方网站或任何包含所需信息的具体页面。例如,要获取最新的比赛得分表单页: ```python url = 'https://www.nba.com/scores' driver.get(url) time.sleep(5) # 给予额外的时间让动态内容完全加载完毕 html_content = driver.page_source ``` #### 解析 HTML 内容 利用 BeautifulSoup 来解析返回的 HTML 文档,提取感兴趣的元素,比如表格中的行记录: ```python from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, "lxml") table_body = soup.find('tbody') rows = table_body.find_all('tr') for row in rows: columns = row.find_all('td') data_row = [ele.text.strip() for ele in columns] print(data_row) ``` #### 关闭浏览器会话 完成操作后记得关闭浏览器窗口以释放资源: ```python driver.quit() ``` 上述代码片段展示了如何配置和使用 Selenium 进行基本的数据采集工作流。对于更复杂的需求,则可能还需要考虑异常处理机制、登录验证流程等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值