2015-01-10 2 views
3

학술적 목적으로 스파이더/웹 크롤러를 작성하여 학술지의 텍스트를 가져 와서 관련 링크를 URL 스택에 추가하려고합니다. 'PubMed'라는 웹 사이트를 크롤링하려고합니다. 나는 내가 필요로하는 링크를 움켜 잡을 수없는 것처럼 보입니다. 이 모두가 한 화면 폭에 맞게 할 수 있도록 그냥 가독성을 위해 여러 변수에 아래의 HTML 트리를 파괴 한python으로 깊이 매몰 된 링크를 다듬는 방법 beautifulSoup

website = 'http://www.ncbi.nlm.nih.gov/pubmed/?term=mtap+prmt' 
from bs4 import BeautifulSoup 
import requests 
r = requests.get(website) 
soup = BeautifulSoup(r.content) 

예를 들면 다음과 같습니다 페이지 내 코드는,이 페이지를 자신의 데이터베이스에있는 다른 사람들을 대표한다이다 .

key_text = soup.find('div', {'class':'grid'}).find('div',{'class':'col twelve_col nomargin shadow'}).find('form',{'id':'EntrezForm'}) 
side_column = key_text.find('div', {'xmlns:xi':'http://www.w3.org/2001/XInclude'}).find('div', {'class':'supplemental col three_col last'}) 
side_links = side_column.find('div').findAll('div')[1].find('div', {'id':'disc_col'}).findAll('div')[1] 

for link in side_links: 
     print link 

당신은 크롬 검사를 사용하여 HTML 소스 코드를 보면 요소 'side_links'내 링크와 함께 다른 여러 가지 중첩 된 div가 있어야한다. 그러나 위의 코드는 다음과 같은 오류가 발생합니다 : 당신이 URL로 이동하는 경우

Traceback (most recent call last): 
File "C:/Users/ballbag/Copy/web_scraping/google_search.py", line 22, in <module> 
side_links = side_column.find('div').findAll('div')[1].find('div',  {'id':'disc_col'}).findAll('div')[1] 
IndexError: list index out of range 

내가 긁어하고자하는 URL을 포함 '관련 링크'라고 오른쪽에 열이있다. 그러나 나는 그들에게 다가 갈 수 없다. div 아래에 들어가려고하고있는 진술이 있습니다. 그리고 이것과 관련이 있다고 생각합니다. 누구든지이 링크를 잡을 수 있습니까? 난 정말 어떤 포인터를 주시면 고맙겠습니다

+0

나는 심지어 OP 찾던 찾을 수 없습니다 –

+0

죄송 – user3062260

답변

3

문제는 사이드 바 추가 비동기 요청으로로드됩니다.

  • requests.Session
  • 사이드 바
  • 해당 링크를 따라에서 링크를 얻을 수를 얻기 위해 사용되는 URL을 구문 분석 사용하여 웹 스크래핑 세션을 유지 :

    생각이 여기에있을 것입니다 div

class="portlet_content"와 코드 :

from urlparse import urljoin 

from bs4 import BeautifulSoup 
import requests 


base_url = 'http://www.ncbi.nlm.nih.gov' 
website = 'http://www.ncbi.nlm.nih.gov/pubmed/?term=mtap+prmt' 

# parse the main page and grab the link to the side bar 
session = requests.Session() 
soup = BeautifulSoup(session.get(website).content) 

url = urljoin(base_url, soup.select('div#disc_col a.disc_col_ph')[0]['href']) 

# parsing the side bar 
soup = BeautifulSoup(session.get(url).content) 

for a in soup.select('div.portlet_content ul li.brieflinkpopper a'): 
    print a.text, urljoin(base_url, a.get('href')) 

인쇄 :

The metabolite 5'-methylthioadenosine signals through the adenosine receptor A2B in melanoma. http://www.ncbi.nlm.nih.gov/pubmed/25087184 
Down-regulation of methylthioadenosine phosphorylase (MTAP) induces progression of hepatocellular carcinoma via accumulation of 5'-deoxy-5'-methylthioadenosine (MTA). http://www.ncbi.nlm.nih.gov/pubmed/21356366 
Quantitative analysis of 5'-deoxy-5'-methylthioadenosine in melanoma cells by liquid chromatography-stable isotope ratio tandem mass spectrometry. http://www.ncbi.nlm.nih.gov/pubmed/18996776 
... 
Cited in PMC http://www.ncbi.nlm.nih.gov/pmc/articles/pmid/23265702/citedby/?tool=pubmed 
+0

'관련 인용 PubMed에에'해당 페이지에있는 모든'관련 링크를'표시되지 않습니다! –

+0

@PadraicCunningham은 인터넷을 통해 상상력을 자극하거나 생각을 시작합니다! :) 감사. – alecxe

+0

감사합니다. 코드 단어가 완벽합니다. 하지만 내 이해를 위해서, 당신은 줄에서 'href'를 어디에서 찾았습니까? "url = urljoin (base_url, soup.select ('div # disc_col a.disc_col_ph') [0] [ 'href'])". div로 이동할 수 있지만 'chromes inspect element'는 html의 해당 섹션에 링크가 표시되지 않습니다. 코드가 작동하더라도 div # disc_col에 'a'링크가 표시되지 않습니다. 기본 URL에서 관련 섹션을 찾을 수도 없습니다. 내 이해를 돕기 위해 기사를 추천 할 수 있다면 좋을 것입니다. 그렇지 않으면, 어쨌든 고마워요. – user3062260

관련 문제