Advertisement
Artemii_Kravtsov

Untitled

Dec 15th, 2020 (edited)
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. import csv
  2. import requests
  3. import re
  4. from bs4 import BeautifulSoup as BS
  5.  
  6. web_page = BS(requests.get('https://developer.mozilla.org/en/docs/Web/CSS/color_value').text)
  7. web_page = web_page.find('table', id = 'colors_table').find('tbody')
  8. file = open('colors.csv', 'w')
  9. writer = csv.DictWriter(file, fieldnames = ['specification', 'keyword', 'rgb_hex_value'])
  10. writer.writeheader()
  11.  
  12. for row in web_page.find_all('tr'):
  13.     data = row.find_all('td')
  14.    
  15.     # В каждом <tr> либо три, либо четыре <td>. Если четыре, то первым <td> будет тот, который содержит
  16.     # значение столбца 'specification' (для себя и для последующих строк, пока не встретится
  17.     # очередная строка с четырьмя <td>). Я проверяю, есть ли в первом <td> очередной строки что-то похожее на значение
  18.     # 'specification' (можно было бы сделать проще: 'if len(data) == 4').
  19.     # Если есть, то меняю '&nbsp;' и '\xa0' на пробел и обновляю переменную 'specification'. Если нет, то
  20.     # 'specification' в этой строчке остаётся "старым", а остальные переменные обновляю.
  21.    
  22.     first_column_text = data[0].text
  23.     if re.match('CSS .+', first_column_text):
  24.         specification = re.sub('(&nbsp;)|(\xa0)', ' ', first_column_text)
  25.         keyword = data[1].find('code').text
  26.         rgb_hex_value = data[2].text
  27.     else:
  28.         keyword = data[0].find('code').text
  29.         rgb_hex_value = data[1].text
  30.    
  31.     writer.writerow({'specification': specification,
  32.                      'keyword': keyword,
  33.                      'rgb_hex_value': rgb_hex_value})
  34.  
  35. file.close()
  36. pd.read_csv('colors.csv')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement