Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CSS selectors to retrieve specific links lying in some class using BeautifulSoup?

I am new to Python and I am learning it for scraping purposes I am using BeautifulSoup to collect links (i.e href of 'a' tag). I am trying to collect the links under the "UPCOMING EVENTS" tab of site http://allevents.in/lahore/. I am using Firebug to inspect the element and to get the CSS path but this code returns me nothing. I am looking for the fix and also some suggestions for how I can choose proper CSS selectors to retrieve desired links from any site. I wrote this piece of code:

from bs4 import BeautifulSoup  import requests  url = "http://allevents.in/lahore/"  r  = requests.get(url)  data = r.text  soup = BeautifulSoup(data) for link in soup.select( 'html body div.non-overlay.gray-trans-back div.container div.row div.span8 div#eh-1748056798.events-horizontal div.eh-container.row ul.eh-slider li.h-item div.h-meta div.title a[href]'):     print link.get('href') 
like image 710
Flecha Avatar asked Jul 17 '14 10:07

Flecha


People also ask

How do you use a selector in BeautifulSoup?

BeautifulSoup provides us select() and select_one() methods to find by css selector. select(): returns all the matching elements. select_one(): returns the first matching element.

What are the 3 main ways we can select an item through CSS?

Simple selectors (select elements based on name, id, class) Combinator selectors (select elements based on a specific relationship between them) Pseudo-class selectors (select elements based on a certain state)

What is CSS selector in web scraping?

Web Scraper uses css selectors to find HTML elements in web pages and to extract data from them. When selecting an element the Web Scraper will try to make its best guess what the CSS selector might be for the selected elements.

What is nested selector?

Nesting Selector: the & selector. When using a nested style rule, one must be able to refer to the elements matched by the parent rule; that is, after all, the entire point of nesting. To accomplish that, this specification defines a new selector, the nesting selector , written as & (U+0026 AMPERSAND).


1 Answers

The page is not the most friendly in the use of classes and markup, but even so your CSS selector is too specific to be useful here.

If you want Upcoming Events, you want just the first <div class="events-horizontal">, then just grab the <div class="title"><a href="..."></div> tags, so the links on titles:

upcoming_events_div = soup.select_one('div.events-horizontal') for link in upcoming_events_div.select('div.title a[href]'):     print(link['href']) 

Note that you should not use r.text; use r.content and leave decoding to Unicode to BeautifulSoup. See Encoding issue of a character in utf-8

like image 170
Martijn Pieters Avatar answered Sep 19 '22 13:09

Martijn Pieters