Как парсить не все ссылки на видео?
Есть парсер, который переходит по ссылкам, которые он берет из csv-файла и парсит с этих страниц видео, но есть одна проблема: если на странице несколько видео, то он парсит все видео, а мне надо, чтобы он парсил только первое видео.
import requests
from bs4 import BeautifulSoup
import csv
FILE="games.csv"
def get_html(url):
r = requests.get(url)
r.encoding = 'utf8'
return r.text
def get_link(html):
soup = BeautifulSoup(html, 'lxml')
video = soup.find_all('div', attrs={"class": "highlight_player_item", "data-mp4-hd-source": True})
for item in video:
games.append({'video':item["data-mp4-hd-source"]})
def save_file(items, path):
with open(path, 'w', newline='', encoding='cp1251') as file:
writer = csv.writer(file, delimiter=';')
writer.writerow(['VIDEOS','LINK'])
for item in items:
writer.writerow([item['video']])
games=[]
with open("racesru.csv", newline='', encoding='cp1251') as csvfile:
reader = csv.reader(csvfile, delimiter=';')
for row in reader:
link = row[4]
if (link != '0' and link != 'LINK'):
url = link
print(url)
save_file(games, FILE)
get_link(get_html(str(url)))
Ответы (1 шт):
Автор решения: Jack_oS
→ Ссылка
Можно ограничить цикл добавления в games срезом:
def get_link(html):
soup = BeautifulSoup(html, 'lxml')
video = soup.find_all('div', attrs={"class": "highlight_player_item", "data-mp4-hd-source": True})
for item in video[1:]:
games.append({'video': item["data-mp4-hd-source"]})
video[1:] - от второго элеманта и до конца,
или брать только первую ссылку на видео методом .find():
def get_link(html):
soup = BeautifulSoup(html, 'lxml')
video = soup.find('div', attrs={"class": "highlight_player_item", "data-mp4-hd-source": True})
games.append({'video': video["data-mp4-hd-source"]})