Neste exemplo, recuperei o URL “https://www.urbandictionary.com/define.php?term=YOLO” e guardei o HTML no ficheiro test_output.html.
(scrapy_env) mihai@DESKTOP-0RN92KH:~/myproject$ scrapy shell --nolog
[s] Available Scrapy objects:
[s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s] crawler <scrapy.crawler.Crawler object at 0x7f1eef80f6a0>
[s] item {}
[s] settings <scrapy.settings.Settings object at 0x7f1eef80f4c0>
[s] Useful shortcuts:
[s] fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)
[s] fetch(req) Fetch a scrapy.Request and update local objects
[s] shelp() Shell help (print this help)
[s] view(response) View response in a browser
>>> response // response is empty
>>> fetch('https://www.urbandictionary.com/define.php?term=YOLO')
>>> response
<200 https://www.urbandictionary.com/define.php?term=Yolo>
>>> with open('test_output.html', 'w') as f:
... f.write(response.text)
...
118260
Agora vamos inspecionar o test_output.html e identificar os seletores de que precisamos para extrair os dados para o nosso scraper do Urban Dictionary.
Podemos observar que:
- Cada contêiner de definição de palavra possui a classe “definition”.
- O significado da palavra encontra-se dentro do div com a classe «meaning».
- Os exemplos da palavra encontram-se dentro do div com a classe «example».
- As informações sobre o autor e a data da publicação encontram-se dentro do div com a classe “contributor”.
Agora vamos testar alguns seletores no Scrapy Shell:
Para obter referências a todos os contentores de definição, podemos usar seletores CSS ou XPath:
Pode saber mais sobre seletores XPath aqui: https://www.webscrapingapi.com/the-ultimate-xpath-cheat-sheet
definitions = response.css('div.definition')
definitions = response.xpath('//div[contains(@class,"definition")]')
Devemos extrair o significado, o exemplo e as informações da publicação de cada contentor de definição. Vamos testar alguns seletores com o primeiro contentor:
>>> first_def = definitions[0]
>>> meaning = first_def.css('div.meaning').xpath(".//text()").extract()
>>> meaning
['Yolo ', 'means', ', '', 'You Only Live Once', ''.']
>>> meaning = "".join(meaning)
>>> meaning
'Yolo means, 'You Only Live Once'.'
>>> example = first_def.css('div.example').xpath(".//text()").extract()
>>> example = "".join(example)
>>> example
'"Put your seatbelt on." Jessica said.\r"HAH, YOLO!" Replies Anna.\r(They then proceed to have a car crash. Long story short...Wear a seatbelt.)'
>>> post_data = first_def.css('div.contributor').xpath(".//text()").extract()
>>> post_data
['by ', 'Soy ugly', ' April 24, 2019']
Ao utilizar o Scrapy Shell, conseguimos encontrar rapidamente um seletor geral que se adequa às nossas necessidades.
definition.css('div.<meaning|example|contributor>').xpath(".//text()").extract()
// returns an array with all the text found inside the <meaning|example|contributor>
ex: ['Yolo ', 'means', ', '', 'You Only Live Once', ''.']
Para saber mais sobre os seletores do Scrapy, consulte a documentação. https://docs.scrapy.org/en/latest/topics/selectors.html