【发布时间】:2022-01-13 14:18:54
【问题描述】:
我需要遍历给定数据字典中的每个 html,以获取包含“Ένδικα Μέσα”的 td 元素及其相邻单元格的内容。谢谢。
这是我正在处理的代码:
from bs4 import BeautifulSoup
import requests
URL = 'https://www.epant.gr/apofaseis-gnomodotiseis/itemlist/category/78-2021.html'
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36",
"X-Amzn-Trace-Id": "Root=1-61acac03-6279b8a6274777eb44d81aae",
"X-Client-Data": "CJW2yQEIpLbJAQjEtskBCKmdygEIuevKAQjr8ssBCOaEzAEItoXMAQjLicwBCKyOzAEI3I7MARiOnssB" }
page = requests.get(URL, headers = headers)
soup = BeautifulSoup(page.content,'html.parser')
baseUrl = 'https://www.epant.gr'
data = {}
for href in [x['href'] for x in soup.select('a[href*=category]:has(span)')]:
page = requests.get(f'{baseUrl}{href}', headers = headers)
soup = BeautifulSoup(page.content,'html.parser')
data[href.split('-')[-1].split('.')[0]] = {
'url': f'{baseUrl}{href}'
}
data[href.split('-')[-1].split('.')[0]]['cases'] = [f'{baseUrl}{x["href"]}' for x in soup.select('h3 a')]
#Search every case-hmtl for "Ένδικα Μέσα" content
from bs4 import BeautifulSoup
import requests
import re
for url2 in data :
headers1 = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36",
"X-Amzn-Trace-Id": "Root=1-61acac03-6279b8a6274777eb44d81aae",
"X-Client-Data": "CJW2yQEIpLbJAQjEtskBCKmdygEIuevKAQjr8ssBCOaEzAEItoXMAQjLicwBCKyOzAEI3I7MARiOnssB" }
page = requests.get(url2, headers = headers1)
soup = BeautifulSoup(page.content,"html.parser")
if soup.find('td', text = "Ένδικα Μέσα").parent.get_text(strip=True) is TRUE :
reqs = requests.get(url2)
soup2 = BeautifulSoup(reqs.text, 'html.parser')
print(url2.get('href'))
row = soup.find('td', text = "Ένδικα Μέσα").parent.get_text(strip=True)
print(row)
P.S.:如果我的帖子需要编辑或格式化,请告诉我。谢谢。
编辑:当我输入您(HedgeHog)提供的代码时,我收到了 SSL 异常错误。
我搜索了一个解决方案并遇到了这个。
proxy = 'http://78.130.136.2:8080'
有了它,我的代码可以完美运行。 谢谢!
【问题讨论】:
标签: python html dictionary web-scraping beautifulsoup