Beautifulsoup lib basics

Beautifulsoup python parsing library general notes.

beautifulsoup parsing with скрэпер and Программирование|lower


USE BEAUTIFUL-SOUP PYTHON LIBRARY TO CREATE SCRAPER BOT FOR WEB PARSING

1. To made HTTP request from python script:

import requests

h = {'DNT':'1','X-Request-Id': 'mss','X-Powered-By': 'Aspress'}

w = requests.get("https://2ip.ru",headers=h)

print(w.request.headers)

print(w.text)

2. To make POST request use request.post(url,data={'key':'value'}) instead of request.get() and so on.

3. To install Beautifulsoup from virtual enviroment $ pip install beautifulsoup4

4. To use import requests

import requests

from bs4 import BeautifulSoup as b

	URL = "https://wikipedia.com"
	page = requests.get(URL)
	soup = b(page.content, "html.parser")

5. To get ID use res = soup.find(id="Some-id") or soup.select("h3 a")

6. To get element by class name el = res.find_all("div", class_="someclass")

7. To send some parameters with GET use:

pl = {'k1': 'val1', 'k2': 'val2'}

requests.get('http://wikipedia.org/', params=pl) // It makes wikipedia.org/get?k2=val2&k1=val1

8. To check if response is successful use print(w.status_code)

9. To get next page try to use next_page = soup.select_one("li.next a")

10. To set attribute for BS element s1[3].string='101'

11. How to get string from beautifulsoup // element[0].text

12. How to strip tags from html // text = soup.get_text() 

13. How to check parameter within a html tag // soup.find_all("img", {"alt": re.compile("^*$")}) but better use re.compile(".*")

14. How to get attribute value from an element.