if ( $curl = curl_init () ) //инициализация сеанса
{
curl_setopt ($curl, CURLOPT_URL, 'http://stocks.investfunds.ru/stocks/'.$code.'/dividend/');//указываем адрес страницы
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_POST, true);
curl_setopt ($curl, CURLOPT_HEADER, 0);
$result = curl_exec ($curl);//выполнение запроса
curl_close ($curl);//закрытие сеанса
}
$html = phpQuery::newDocumentHTML($result);
phpQuery::selectDocument($html);
$a = [1,3,5]; //номера столбцов из которых надо извлечь данные(год, дата выплаты и сумма)
$emitent_string = htmlentities(pq('h1')->text(),ENT_COMPAT,'UTF-8');
if ($emitent_string === ""){
$divs['emitent'] = 'Нет эмитента';
return $divs;
}
$re = [' акция привилегированная, Дивиденды', ' акция обыкновенная, Дивиденды',' акция обыкновенная',' акция привилегированная'];
$emi = str_replace($re,'',$emitent_string);
$divs['emitent'] = $emi;
$divs['code'] = $code;
/*находим количество лет, когда выплачивали дивы*/
$i = pq('[cellpadding="0"] tr td:nth-child(1)');
$l = substr_count($i,'td style');
/*помечаем, что эмитент не выплачивал дивы*/
if ($l === 0){
$divs['data']= 'No divs';
return $divs;
}
/******играемся с регулярными выражениями и css************************/
for ($i =3;$i<$l+3;$i++){
foreach ($a as $j){
switch ($j) {
case 1:
$divs['data'][$i-2]['year'] = str_replace(' ','',htmlentities(pq("[cellpadding='0'] tr:nth-child($i) td:nth-child($j)")->text(),ENT_COMPAT,'UTF-8'));
break;
case 3:
$divs['data'][$i-2]['date'] = str_replace(' ','',htmlentities(pq("[cellpadding='0'] tr:nth-child($i) td:nth-child($j)")->text(),ENT_COMPAT,'UTF-8'));
break;
case 5:
$string = htmlentities(pq("[cellpadding='0'] tr:nth-child($i) td:nth-child($j)")->text(),ENT_SUBSTITUTE,'UTF-8');
$re = '/[ \s]|[руб]/';
$divs['data'][$i-2]['price'] = (float)preg_replace($re,'',$string);
break;
default:
break;
}
}
}
/*возвращаем массив, который содержит в себе название эмитента, год выплаты, дату выплаты и сумму выплаты */
return $divs;
}
The PHP code you've provided is a function that scrapes dividend data from a specific website for a given stock code. To convert this into equivalent Python code, we can use libraries such as requests for handling HTTP requests and BeautifulSoup or lxml for parsing HTML content.
Here is how you might rewrite that function in Python:
import requests
from bs4 import BeautifulSoup
import re
def get_divs_from_code(code):
# Base URL format for fetching data
base_url = 'http://stocks.investfunds.ru/stocks/{}/dividend/'
# Making a GET request to fetch data
response = requests.get(base_url.format(code))
if response.status_code != 200:
print("Failed to retrieve data")
return
# Parsing the HTML content using BeautifulSoup
soup = BeautifulSoup(response.content, 'html.parser')
# Finding the emitent info
emitent_header = soup.find('h1')
emitent_string = emitent_header.get_text(strip=True) if emitent_header else ""
# Default response data
divs = {'emitent': 'Нет эмитента', 'code': code}
if emitent_string == "":
return divs
# Cleaning up emitent name
replacements = [' акция привилегированная, Дивиденды', ' акция обыкновенная, Дивиденды',' акция обыкновенная',' акция привилегированная']
for r in replacements:
emitent_string = emitent_string.replace(r, '')
divs['emitent'] = emitent_string
# Finding data rows
data_rows = soup.select('[cellpadding="0"] tr:not(:first-child)')
if not data_rows:
divs['data'] = 'No divs'
return divs
# Extracting data for each year
divs['data'] = []
for row in data_rows:
cells = row.find_all('td')
if len(cells) >= 5:
year = cells[0].get_text(strip=True)
date = cells[2].get_text(strip=True)
# Cleaning up price string
price_string = cells[4].get_text(strip=True)
price_string = re.sub('[\s]|[руб]', '', price_string)
try:
price = float(price_string)
except ValueError:
price = None
divs['data'].append({
'year': year,
'date': date,
'price': price
})
return divs
In this Python code:
- The
requests library is used to send an HTTP GET request and retrieve the HTML content.
- The
BeautifulSoup library is used to parse HTML and extract information.
- The regular expression is used to clean up the price string.
Please note that this code assumes that the structure of the HTML page at the specified URL follows a predictable format and that this script respects the terms of use for the website it is scraping. Web scraping may violate the terms of service of some websites, so make sure you have permission or legal rights to scrape the website in question.