2017-10-03 8 views
0

이 웹 사이트의 기사를 웹 크롤링 할 예정입니다. 웹 페이지에서 기사 텍스트를 추출하는 Xpath

내가 지금까지 무엇을했는지 있습니다 :

# HR Version 
# the entire crawling process 

openfile = open("data/HR.csv", "rb") 
r = csv.reader(openfile) 
HR_data = [] 

for i in r: 
    url = i[0] 
    print url # to know the status of web crawling 
    r = requests.get(url) 
    data = html.fromstring(r.text) 
    #Inspect line with text 
    #//*[@id="article-details"] 
    #<section class="entry-content clearfix" itemprop="articleBody"></section> 
    texts = data.xpath("//*[@id="article-details"]/p/text()") 
    raw = ''.join(str(i.encode("utf-8")) for i in texts) 
    finaldata = raw.replace('\r','').replace('\n','').replace('\r','').replace('\t','')  
    HR_data.append([finaldata]) 

openfile.close() 

문제의 명령은 다음과

texts = data.xpath("//*[@id="article-details"]/p/text()") 

그리고이 특정 웹 페이지에서의 : http://hrmagazine.co.uk/article-details/internal-entrepreneurship-can-boost-your-business

에 요소를 검사하여 파이어 폭스, "텍스트"가 다음 섹션에 포함되어 있음을 발견했습니다 :

<article id="article-details"> 
#One <h2> element, followed by multiple <p> elements. 
</article> 

기사에서 단락 텍스트 만 추출하는 올바른 XPath는 무엇입니까?

답변

0

거의 올바른 XPath를 작성했습니다. ph2

texts = data.xpath("//*[@id="article-details"]/h2/text()") 
으로 대체해야합니다.