python - python beautifulsoup - 如何在下一页没有唯一地址时转到下一页
问题描述
我正在尝试使用 beautifulsoup 编写一个网络爬虫,以从https://www.ncbi.nlm.nih.gov/gene/?term=Celiac+disease中提取基因名称
我的代码可以从第一页得到我想要的结果,但我不知道如何编写代码让我的程序移动到下一页。单击“下一步”按钮后,我得到一个与上一页无关的新地址。例如,第一页的地址是https://www.ncbi.nlm.nih.gov/gene/?term=Celiac+disease,但下一页的地址是https://www.ncbi.nlm.nih。 gov/gene(但仍显示与乳糜泻相关的结果)
我查了google和stackoverflow,看看有没有与这个问题相关的文章。但我只能找到有关具有相似地址的页面的文章,并且(对我而言)逻辑上遵循他们的轨迹。
from bs4 import BeautifulSoup
from urllib.request import urlopen
gene_result = []
url = "https://www.ncbi.nlm.nih.gov/gene/?term=Celiac+disease"
html = urlopen(url).read()
soup = BeautifulSoup(html, "html5lib")
tbody = soup.find("tbody")
a_href = tbody.find_all("a")
for x in a_href:
gene = x.contents[0]
gene_result.append(gene)
print(gene_result)
代码很好地抓取了第一页,我得到了很好的结果:
['CTLA4', 'HLA-DQA1', 'IL2', 'IL21', 'CCR3', 'CELIAC2', 'ATXN2', 'SH2B3', 'HLA-DQB1', 'CELIAC5', 'TAGAP', 'CELIAC7', 'CELIAC13', 'CELIAC12', 'CELIAC11', 'CELIAC10', 'CELIAC9', 'CELIAC8', 'CELIAC6', 'KIAA1109']
有人可以帮我解决这个问题吗?
解决方案
对于这样的网站,您需要在python 中使用称为 selenium webdriver 的东西。
您将需要从您的 python 代码中通过此 web 驱动程序模拟单击“下一步”按钮,然后将 html_source 读入 BeautifulSoup。
推荐阅读
- x86 - 单个内核可以一次执行多个比较/添加操作吗?
- c++ - 尝试从 Octave 的独立程序示例中编译示例代码,在第一行出现段错误
- python - 遍历维度的子集
- hyperledger-fabric - 在 ubuntu 18.04 LTS 中执行“npm install”命令时出错
- android - NotificationListenerService tickerText 对于某些应用程序是空的
- node.js - 使用异步等待从 csv 文件创建或更新行,创建多行而不是更新
- html - 使body宽度对应于div的存在
- reactjs - React 中的状态是什么?
- android - 当表达式不适用于 onCreateDrawableState 中的枚举类时 - android、kotlin
- javascript - 在快速车把中配置文件扩展名