python beautifulsoup-当下一页没有唯一地址时如何转到下一页

时间:2018-12-28 17:12:01

标签: python web-scraping beautifulsoup web-crawler

我正在尝试编写一个使用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']

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

1 个答案:

答案 0 :(得分:0)

对于此类网站,您需要使用selenium webdriver with python.

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