网页抓取-基本库存

时间:2018-12-06 21:29:59

标签: python beautifulsoup python-requests

我正试图从investing.com获取土耳其股票的市场价值。 这是我的代码:

import requests
from bs4 import BeautifulSoup

url = "https://tr.investing.com/equities/turkey"
heads = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'}
response = requests.get(url, headers=heads)
html_icerigi = response.text
soup = BeautifulSoup(html_icerigi, "html.parser")
stock= soup.find_all("td",{"class":"bold left noWrap elp plusIconTd"})
value=soup.find_all("td",{"class":"pid-19260-last"})
stocks= []
i=1
for stock1,value1 in zip(stock,value):
stocks.append(["{}: ".format(i) + stock1.text.strip()+"-->"+value1.text.strip()])
i+=1
list(stocks)

问题是我想把所有的“ class”都汤掉:“ pid-***-last”。我怎么能得到这个?

2 个答案:

答案 0 :(得分:3)

使用重新编译

import re
value = soup.find_all("td", class_=re.compile("pid-.+-last"))
与class_一起使用的

re.compile允许您传入正则表达式作为类名。这个正则表达式表示要将类与字面上的“ pid-”,任意数量的通配符以及字面上的“ -last”进行匹配。

https://regex101.com

答案 1 :(得分:3)

您可以使用CSS选择器。我使用adjacent sibling combinator (+)来确保通过位置获得last值。这将比通过HTML正则表达式更快。<​​/ p>

import requests
from bs4 import BeautifulSoup

url = "https://tr.investing.com/equities/turkey"
heads = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'}
response = requests.get(url, headers=heads)
html_icerigi = response.text
soup = BeautifulSoup(html_icerigi, "html.parser")
items = [item.text for item in soup.select('.bold.left.noWrap.elp.plusIconTd')]
values = [value.text for value in soup.select("#cross_rate_markets_stocks_1 .bold.left.noWrap.elp.plusIconTd + td")]
stocks = list(zip(items,values))