Как получить вложенный href в python? - PullRequest
1 голос
/ 24 марта 2020

GOAL

(мне нужно многократно выполнять поиск сотни раз):

1. Поиск (например, "WP_000177210.1") в "https://www.ncbi.nlm.nih.gov/ipg/ "

(т. Е. https://www.ncbi.nlm.nih.gov/ipg/?term=WP_000177210.1)

2. Выбрать первую запись во втором столбце" CDS Region in Nucleotide "таблицы

(то есть" NC_011415.1 1997353-1998831 (-) ", https://www.ncbi.nlm.nih.gov/nuccore/NC_011415.1?from=1997353&to=1998831&strand=2)

3. Выберите «FASTA» под названием этой последовательности

4. Получить последовательность фаста

(то есть "> NC_011415.1: c1998831-1997353 Escherichia coli SE11 , полная последовательность * "

import requests
from bs4 import BeautifulSoup

url = "https://www.ncbi.nlm.nih.gov/ipg/"
r = requests.get(url, params = "WP_000177210.1")
if r.status_code == requests.codes.ok:
    soup = BeautifulSoup(r.text,"lxml")

2. Выберите первую запись во втором столбце" Область CDS в нуклеотиде "таблицы (в данном случае" NC_011415.1 1997353-1998831 (-) ") (то есть https://www.ncbi.nlm.nih.gov/nuccore/NC_011415.1?from=1997353&to=1998831&strand=2)

# try 1 (wrong)
## I tried this first, but it seemed like it only accessed to the first level of the href?!
for a in soup.find_all('a', href=True):
    if (a['href'][:8]) =="/nuccore":
        print("Found the URL:", a['href'])

# try 2 (not sure how to access nested href)
## According to the label I saw in the Develop Tools, I think I need to get the href in the following nested structure. However, it didn't work.
soup.select("html div #maincontent div div div #ph-ipg div table tbody tr td a")

Я застрял в этом шаге прямо сейчас ....

PS

Я впервые имею дело с html форматом. Я также впервые задаю вопрос здесь. Я не мог бы сформулировать проблему очень хорошо. Если что-то не так, пожалуйста, дайте мне знать.

1 Ответ

0 голосов
/ 27 марта 2020

Без использования REST API NCBI,

import time
from bs4 import BeautifulSoup
from selenium import webdriver

# Opens a firefox webbrowser for scrapping purposes
browser = webdriver.Firefox(executable_path=r'your\path\geckodriver.exe') # Put your own path here

# Allows you to load a page completely (with all of the JS)
browser.get('https://www.ncbi.nlm.nih.gov/ipg/?term=WP_000177210.1')

# Delay turning the page into a soup in order to collect the newly fetched data
time.sleep(3)

# Creates the soup
soup = BeautifulSoup(browser.page_source, "html")

# Gets all the links by filtering out ones with just '/nuccore' and keeping ones that include '/nuccore'
links = [a['href'] for a in soup.find_all('a', href=True) if '/nuccore' in a['href'] and not a['href'] == '/nuccore']

Примечание:

Вам понадобится пакет selenium

Вам нужно будет установить GeckoDriver

...