Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- import requests
- import re
- from bs4 import BeautifulSoup as BS
- web_page = BS(requests.get('https://developer.mozilla.org/en/docs/Web/CSS/color_value').text)
- web_page = web_page.find('table', id = 'colors_table').find('tbody')
- file = open('colors.csv', 'w')
- writer = csv.DictWriter(file, fieldnames = ['specification', 'keyword', 'rgb_hex_value'])
- writer.writeheader()
- for row in web_page.find_all('tr'):
- data = row.find_all('td')
- # В каждом <tr> либо три, либо четыре <td>. Если четыре, то первым <td> будет тот, который содержит
- # значение столбца 'specification' (для себя и для последующих строк, пока не встретится
- # очередная строка с четырьмя <td>). Я проверяю, есть ли в первом <td> очередной строки что-то похожее на значение
- # 'specification' (можно было бы сделать проще: 'if len(data) == 4').
- # Если есть, то меняю ' ' и '\xa0' на пробел и обновляю переменную 'specification'. Если нет, то
- # 'specification' в этой строчке остаётся "старым", а остальные переменные обновляю.
- first_column_text = data[0].text
- if re.match('CSS .+', first_column_text):
- specification = re.sub('( )|(\xa0)', ' ', first_column_text)
- keyword = data[1].find('code').text
- rgb_hex_value = data[2].text
- else:
- keyword = data[0].find('code').text
- rgb_hex_value = data[1].text
- writer.writerow({'specification': specification,
- 'keyword': keyword,
- 'rgb_hex_value': rgb_hex_value})
- file.close()
- pd.read_csv('colors.csv')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement