python下载上市公司年报
时间: 2023-11-20 14:58:11 浏览: 38
以下是使用Python下载上市公司年报的步骤:
1. 首先需要安装Selenium和ChromeDriver,Selenium用于模拟浏览器操作,ChromeDriver用于控制Chrome浏览器。可以使用以下命令安装Selenium和ChromeDriver:
```shell
pip install selenium
```
2. 导入必要的包:
```python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import os
import pandas as pd
from time import sleep
```
3. 启动Chrome浏览器并打开目标网站:
```python
# 启动Chrome浏览器
driver = webdriver.Chrome()
# 打开目标网站
driver.get("http://www.cninfo.com.cn/new/index")
```
4. 在搜索框中输入公司名称并搜索:
```python
# 找到搜索框并输入公司名称
search_box = driver.find_element(By.ID, "suggestinput")
search_box.send_keys("公司名称")
# 模拟回车键
search_box.send_keys(Keys.RETURN)
```
5. 点击“公司概况”中的“公司公告”:
```python
# 找到“公司概况”并点击
company_info = driver.find_element(By.XPATH, "//a[contains(text(),'公司概况')]")
company_info.click()
# 找到“公司公告”并点击
company_announcement = driver.find_element(By.XPATH, "//a[contains(text(),'公司公告')]")
company_announcement.click()
```
6. 在“公司公告”页面中找到“年报”并点击:
```python
# 找到“年报”并点击
annual_report = driver.find_element(By.XPATH, "//a[contains(text(),'年报')]")
annual_report.click()
```
7. 在“年报”页面中找到目标年份的年报并下载:
```python
# 找到目标年份的年报并下载
year = "2021" # 目标年份
pdf_links = driver.find_elements(By.XPATH, f"//a[contains(text(),'{year}') and contains(text(),'PDF')]")
for link in pdf_links[:2]: # 只下载前两个PDF文件
href = link.get_attribute("href")
driver.execute_script(f"window.open('{href}');")
sleep(2) # 等待2秒钟
```
完整代码如下:
```python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import os
import pandas as pd
from time import sleep
# 启动Chrome浏览器
driver = webdriver.Chrome()
# 打开目标网站
driver.get("http://www.cninfo.com.cn/new/index")
# 找到搜索框并输入公司名称
search_box = driver.find_element(By.ID, "suggestinput")
search_box.send_keys("公司名称")
# 模拟回车键
search_box.send_keys(Keys.RETURN)
# 找到“公司概况”并点击
company_info = driver.find_element(By.XPATH, "//a[contains(text(),'公司概况')]")
company_info.click()
# 找到“公司公告”并点击
company_announcement = driver.find_element(By.XPATH, "//a[contains(text(),'公司公告')]")
company_announcement.click()
# 找到“年报”并点击
annual_report = driver.find_element(By.XPATH, "//a[contains(text(),'年报')]")
annual_report.click()
# 找到目标年份的年报并下载
year = "2021" # 目标年份
pdf_links = driver.find_elements(By.XPATH, f"//a[contains(text(),'{year}') and contains(text(),'PDF')]")
for link in pdf_links[:2]: # 只下载前两个PDF文件
href = link.get_attribute("href")
driver.execute_script(f"window.open('{href}');")
sleep(2) # 等待2秒钟
# 关闭浏览器
driver.quit()
```