2017-10-26 3 views
0

이 뉴스 사이트에서 데이터를 수집하고 싶습니다. http://www.inquirer.net/자바 스크립트 웹 사이트에서 XPath를 사용하여 데이터를 가져 오는 방법은 무엇입니까?

타일에 뉴스 제목을 붙이고 싶습니다.

다음은 검사 코드

당신이 볼 수 있듯이, 이미이 잡아하려는 타일의 제목 중 하나의 스크린 샷입니다. 브라우저에서 xpath를 복사 할 때 // * [@ id = "tgs3_info"]/h2

파이썬 코드를 실행하려고했습니다.

import lxml.html 
import lxml.etree 
import requests 

link = 'http://www.inquirer.net/' 
res = requests.get(link) 
r = res.content 
html_content = lxml.html.fromstring(r) 
root = html_content.xpath('//*[@id="tgs3_info"]/h2') 
print(root) 

그러나 빈 목록을 반환합니다.

나는 여기 stackoverflow와 인터넷에서 대답을 찾으려고 노력했다. 나는 그것을 정말로 얻지 못한다. 사이트의 페이지 원본을 볼 때. 내가 원하는 데이터는 javascript 함수에 없습니다. 그것은 div에 있으므로 왜 데이터를 가져올 수 없는지 이해하지 못합니다. 나는 여기에서 대답을 찾을 수 있었으면 좋겠다. HTTP 오류 403 : 금지 된 오류 Xurasky의 솔루션에서 입력으로

+0

검사의 값을 사용하여이 문제를 해결할 수있다 '는 답변 주셔서 감사합니다 –

답변

0

내가 당신이 urllib.error.HTTPError을 받고 생각 403 오류를

import lxml.html 
import lxml.etree 
from urllib.request import Request, urlopen 

req = Request('http://www.inquirer.net/', headers={'User-Agent': 'Mozilla/5.0'}) 
r = urlopen(req).read() 
html_content = lxml.html.fromstring(r) 
root = html_content.xpath('//*[@id="tgs3_info"]/h2') 
for a in root: 
    print(a.text_content()) 

출력

Duterte, Roque meeting set in Malacañang 
2 senators welcome Ventura's revelations in Atio hazing case 
Paolo Duterte vows to retire from politics in 2019 
NBA: DeMarcus Cousins regrets being loyal to Sacramento Kings 
PH bet Elizabeth Durado Clenci wins 2nd runner-up at Miss Grand International 2017 
DOJ wants Divina, 50 others in `Atio' hazing case added on BI watchlist 
Georgina Wilson Shares Messages From Fans on Baby Blues 
+0

필요한 데이터가 있는지 여부를 r'. 코드를 실행하려고했지만 빈 결과도 반환합니다. – Slet

+0

에는 데이터가 있습니다. Xurasky의 솔루션을 시도했지만 여전히 빈 결과를 반환합니다. – Slet

+0

업데이트 된 게시물이 실제로 필요한 것입니다. 어떻게 작동하는지 설명해 주시겠습니까? 특히이 부분. urlib.request import request, urlopen req = 요청 ('http://www.inquirer.net/', 헤더 = { '사용자 에이전트': 'Mozilla/5.0'}) r = urlopen (req) .read() – Slet

0

을 방지 할 수 있습니다.

당신은

import lxml.html 
import lxml.etree 
from urllib.request import Request, urlopen 

req = Request('http://www.inquirer.net/', headers={'User-Agent': 'Mozilla/5.0'}) 
res = urlopen(req).read() 
html_content = lxml.html.fromstring(r) 
root = html_content.xpath('//*[@id="tgs3_info"]/h2') 
print(root) 
관련 문제