首页 > 解决方案 > 使用 React 脚本从 url 抓取 csv 文件

问题描述

我想从https://depmap.org/portal/download/抓取sample_info.csv文件。由于网站上有一个 React 脚本,因此使用 BeautifulSoup 并通过适当的标签访问文件并不是那么简单。我确实从多个角度处理了这个问题,给我最好结果的那个看起来像这样,它返回执行的脚本,其中所有下载的文件与其他数据一起列出。我当时的想法是剥离标签并将信息存储在 JSON 中。但是,我认为数据中一定存在某种错误,因为不可能将其存储为 JSON。

url = 'https://depmap.org/portal/download/'
html_content = requests.get(url).text
soup = BeautifulSoup(html_content, "lxml")
all_scripts = soup.find_all('script')
script = str(all_scripts[32])
last_char_index = script.rfind("}]")
first_char_index = script.find("[{")
script_cleaned = script[first_char_index:last_char_index+2]
script_json = json.loads(script_cleaned)

这段代码给了我一个错误 JSONDecodeError: Extra data: line 1 column 7250 (char 7249) 我知道我的解决方案可能并不优雅,但它让我最接近目标,即从网站下载sample_info.csv文件。不知道如何在这里进行。如果还有其他选择?我尝试使用 selenium,但由于驱动程序路径声明,此解决方案对我的脚本的最终用户不可行

标签: pythonjsonweb-scrapingbeautifulsoup

解决方案


在这种情况下使用正则表达式可能更容易,因为字符串是无效的 JSON。

此 RegEx 工具 ( https://pythex.org/ ) 可用于测试表达式。

import re
re.findall(r'"downloadUrl": "(.*?)".*?"fileName": "(.*?)"', script_cleaned)
#[
#  ('https://ndownloader.figshare.com/files/26261524', 'CCLE_gene_cn.csv'),
#  ('https://ndownloader.figshare.com/files/26261527', 'CCLE_mutations.csv'),
#  ('https://ndownloader.figshare.com/files/26261293', 'Achilles_gene_effect.csv'),
#  ('https://ndownloader.figshare.com/files/26261569', 'sample_info.csv'),
#  ('https://ndownloader.figshare.com/files/26261476', 'CCLE_expression.csv'),
#  ('https://ndownloader.figshare.com/files/17741420', 'primary_replicate_collapsed_logfold_change_v2.csv'),
#  ('https://gygi.med.harvard.edu/publications/ccle',  'protein_quant_current_normalized.csv'),
#  ('https://ndownloader.figshare.com/files/13515395', 'D2_combined_gene_dep_scores.csv')
# ]

编辑:这也可以通过html_content直接传递(不需要 BeautifulSoup)来工作。

url = 'https://depmap.org/portal/download/'
html_content = requests.get(url).text
re.findall(r'"downloadUrl": "(.*?)".*?"fileName": "(.*?)"', html_content)

推荐阅读