首页 > 解决方案 > 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']

有人可以帮我解决这个问题吗?

标签: pythonweb-scrapingbeautifulsoupweb-crawler

解决方案


对于这样的网站,您需要在python 中使用称为 selenium webdriver 的东西。

您将需要从您的 python 代码中通过此 web 驱动程序模拟单击“下一步”按钮,然后将 html_source 读入 BeautifulSoup。


推荐阅读