python beautifulsoup下载_使用Python和BeautifulSoup从网页下载.xls文件

你的剧本目前的问题是:url有一个尾随的/在请求时给出一个无效的页面,而不是列出要下载的文件。

soup.select(...)中的CSS选择器正在选择具有属性webpartid的div,该属性在链接文档中的任何位置都不存在。

您将加入URL并引用它,即使页面中的链接是作为绝对URL给出的,它们不需要引用。

try:...except:块将阻止您看到在尝试下载文件时生成的错误。在没有特定异常的情况下使用except块是不好的做法,应该避免。

修改后的代码版本将获得正确的文件并尝试下载它们,如下所示:from bs4 import BeautifulSoup

# Python 3.x

from urllib.request import urlopen, urlretrieve, quote

from urllib.parse import urljoin

# Remove the trailing / you had, as that gives a 404 page

url = 'https://www.rbi.org.in/Scripts/bs_viewcontent.aspx?Id=2009'

u = urlopen(url)

try:

html = u.read().decode('utf-8')

finally:

u.close()

soup = BeautifulSoup(html, "html.parser")

# Select all A elements with href attributes containing URLs starting with http://

for link in soup.select('a[href^="http://"]'):

href = link.get('href')

# Make sure it has one of the correct extensions

if not any(href.endswith(x) for x in ['.csv','.xls','.xlsx']):

continue

filename = href.rsplit('/', 1)[-1]

print("Downloading %s to %s..." % (href, filename) )

urlretrieve(href, filename)

print("Done.")

但是,如果运行此命令,您会注意到抛出了urllib.error.HTTPError: HTTP Error 403: Forbidden异常,即使该文件可以在浏览器中下载。

起初我以为这是一个推荐检查(为了防止热链接),但是如果你在浏览器(如Chrome开发工具)中按要求观看,你会注意到

初始的http://请求也在那里被阻止,然后Chrome尝试对同一个文件发出https://请求。

换句话说,请求必须通过HTTPS才能工作(不管页面中的url怎么说)。要解决这个问题,您需要在使用请求的URL之前将http:重写为https:。以下代码将正确修改url并下载文件。我还添加了一个变量来指定输出文件夹,该文件夹使用os.path.join添加到文件名中:import os

from bs4 import BeautifulSoup

# Python 3.x

from urllib.request import urlopen, urlretrieve

URL = 'https://www.rbi.org.in/Scripts/bs_viewcontent.aspx?Id=2009'

OUTPUT_DIR = '' # path to output folder, '.' or '' uses current folder

u = urlopen(URL)

try:

html = u.read().decode('utf-8')

finally:

u.close()

soup = BeautifulSoup(html, "html.parser")

for link in soup.select('a[href^="http://"]'):

href = link.get('href')

if not any(href.endswith(x) for x in ['.csv','.xls','.xlsx']):

continue

filename = os.path.join(OUTPUT_DIR, href.rsplit('/', 1)[-1])

# We need a https:// URL for this site

href = href.replace('http://','https://')

print("Downloading %s to %s..." % (href, filename) )

urlretrieve(href, filename)

print("Done.")

如果原始的xls文件是来自网页的动态内容,通常直接下载得到的是静态页面(如html)而非可以直接导入Excel的xls文件。这种情况下的数据获取通常需要通过网络爬虫(Web Scraping)技术和特定的解析库,比如BeautifulSoup、Scrapy或Selenium等。 以下是基本流程: 1. **网络爬取**:使用像Selenium这样的工具模拟浏览器行为,打开包含动态内容的网页,让其加载动态生成的内容。 ```python from selenium import webdriver driver = webdriver.Firefox() # 根据你的环境选择浏览器驱动 driver.get(url) time.sleep(3) # 等待动态内容加载完成 html_content = driver.page_source driver.quit() ``` 2. **数据解析**:利用BeautifulSoup等库解析HTML内容,找到隐藏在其中的Excel表格数据,这可能需要一些CSS选择器或者XPath的知识。 ```python from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, 'lxml') table_data = soup.select_one('#your_table_id') or soup.find_all('table') # 调整标签名和id ``` 3. **数据转换**:一旦获得到表格数据,可能会是一系列的嵌套字典或列表结构。这时,你需要将它们转换成pandas DataFrame以便后续处理。 ```python import pandas as pd dfs = [] for tr in table_data.find_all('tr'): row_data = [td.text for td in tr.find_all('td')] dfs.append(row_data) data = pd.DataFrame(dfs, columns=header_list) # header_list是你知道的列名 ``` 4. **保存为xls**:最后,你可以将处理好的DataFrame写入新的xls文件。 ```python data.to_excel('dynamic_data.xls', index=False) ``` 需要注意的是,这类操作会遇到一些挑战,比如网站反爬机制、动态加载数据的延迟、以及数据的复杂结构。此外,一定要遵守网站的robots.txt协议和使用条款。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值