Scrapy Body Only - PullRequest
       31

Scrapy Body Only

7 голосов
/ 22 марта 2011

Я пытаюсь вычистить текст только из тела, используя Python Scrapy, но мне пока не повезло.

Желая, чтобы некоторые ученые могли помочь мне здесь соскрести весь текст с <body> tag.

Ответы [ 2 ]

4 голосов
/ 22 марта 2011

Scrapy использует нотацию XPath для извлечения частей HTML-документа. Итак, вы пытались просто использовать путь /html/body для извлечения <body>? (если он вложен в <html>). Селектор //body может быть еще проще:

x.select("//body").extract()    # extract body

Вы можете найти больше информации о селекторах, которые предоставляет Scrapy здесь .

2 голосов
/ 09 июня 2012

Было бы неплохо получить вывод, подобный тому, который выдает lynx -nolist -dump, который отображает страницу, а затем выводит видимый текст. Я подошел ближе, извлекая текст всех дочерних элементов абзаца.

Я начал с //body//text(), который вытягивал все текстовые элементы внутри тела, но это включало элементы скрипта. //body//p получает все элементы абзаца внутри тела, включая подразумеваемый тег абзаца вокруг непомеченного текста. Извлечение текста с помощью //body//p/text() пропускает элементы из подтегей (например, полужирный , курсив , span, div). //body//p//text(), кажется, получает большую часть желаемого контента, если на странице нет встроенных в абзацы тегов скрипта.

в XPath / подразумевает прямого потомка, а // включает всех потомков.

% scrapy shell
In[1]: fetch('/8035111/scrapy-body-only')
In[2]: hxs.select('//body//p//text()').extract()

Out[2]:
[u"I am trying to scrape the text only from body using python Scrapy, but haven't had any luck yet.",
u'Wishing some scholars might be able to help me here scraping all the text from the ',
u'&lt;body&gt;',
u' tag.',
u'Thank you in advance for your time.',
u'Scrapy uses XPath notation to extract parts of a HTML document. So, have you tried just using the ',
u'/html/body',
u' path to extract ',
u'&lt;body&gt;',
u"? (assuming it's nested in ",
u'&lt;html&gt;',
u'). It might be even simpler to use the ',
u'//body',
u' selector:',
u'You can find more information about the selectors Scrapy provides ',
u'here',

Соедините строки вместе с пробелом, и вы получите довольно хороший вывод:

In [43]: ' '.join(hxs.select("//body//p//text()").extract())
Out[43]: u"I am trying to scrape the text only from body using python Scrapy, but haven't had any luck yet. Wishing some scholars might be able to help me here scraping all the text from the  &lt;body&gt;  tag. Thank you in advance for your time. Scrapy uses XPath notation to extract parts of a HTML document. So, have you tried just using the  /html/body  path to extract  &lt;body&gt; ? (assuming it's nested in  &lt;html&gt; ). It might be even simpler to use the  //body  selector: You can find more information about the selectors Scrapy provides  here . This is a collaboratively edited question and answer site for  professional and enthusiast programmers . It's 100% free, no registration required. about \xbb \xa0\xa0\xa0 faq \xbb \r\n             tagged asked 1 year ago viewed 280 times active 1 year ago"
...