Веб-утилизация с Python: проблема с BeautifulSoup - PullRequest
0 голосов
/ 08 июня 2019

Пожалуйста, помогите мне с использованием BeautifulSoup, чтобы очистить веб-страницы от ценностей investing.com с помощью Python 3. Что бы я ни получал, я никогда не получаю никакого значения, и класс регистрации постоянно меняется с веб-страницы, и это реальная ценность.

import requests

from bs4 import BeautifulSoup

url = "https://es.investing.com/indices/spain-35-futures"
precio_objetivo = input("Introduce el PRECIO del disparador:")
precio_objetivo = float(precio_objetivo)
print (precio_objetivo)

while True:
html = requests.get(url).text
soup = BeautifulSoup(html, "html.parser")
precio_actual = soup.find('span', attrs={'class': 'arial_26 inlineblock pid-8828-last','id':'last_last','dir':'ltr'})
print (precio_actual)
break;

Когда я не применяю какой-либо фильтр на sou.find (пытаясь хотя бы получить всю веб-страницу), я получаю такой результат:

<bound method Tag.find_all of 
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
<head>
<title>403 You are banned from this site.  Please contact via a different client configuration if you believe that this is a mistake.                                </title>
</head>
<body>
<h1>Error 403 You are banned from this site.  Please contact via a different client configuration if you believe that this is a mistake.</h1>
<p>You are banned from this site.  Please contact via a different client configuration if you believe that this is a mistake.</p>
<h3>Guru Meditation:</h3>
<p>XID: 850285196</p>
<hr/>
<p>Varnish cache server</p>
</body>
</html>

Ответы [ 2 ]

0 голосов
/ 20 июля 2019

Веб-сервер обнаруживает скрипт python как бот и, следовательно, блокирует его.Используя заголовки, вы можете предотвратить это, и следующий код делает это:

import requests
from bs4 import BeautifulSoup

url = "https://es.investing.com/indices/spain-35-futures"

header={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36'}
page=requests.get(url,headers=header)

soup=BeautifulSoup(page.content,'html.parser')
#this soup returns <span class="arial_26 inlineblock pid-8828-last" dir="ltr" id="last_last">9.182,5</span>

result = soup.find('span',attrs={'id':'last_last'}).get_text()
#use the get_text() function to extract the text

print(result)
0 голосов
/ 30 июня 2019

Похоже, что веб-сайт определяет, откуда поступил запрос, поэтому нам нужно «обмануть» его, думая, что мы в браузере.

from bs4 import BeautifulSoup
from urllib.request import Request, urlopen

r = Request("https://es.investing.com/indices/spain-35-futures", headers={"User-Agent": "Mozilla/5.0"})
c = urlopen(r).read()
soup = BeautifulSoup(c, "html.parser")
print(soup)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...