[英]How do I loop through a list of URLs to print <P> with Beautifulsoup
[英]how to print data between <p> and </p> beautifulsoup
我正在编写一个脚本,以在天气站点上刮擦天气的高潮和低潮,而我已经获得了它来打印我需要的东西,但带有所有Beautifulsoup标签。
这是我当前的脚本:
import urllib2
from bs4 import BeautifulSoup
website = "http://forecast.weather.gov/MapClick.php?lat=39.90489741058809&lon=-82.7617367885212&site=all&smap=1#.VPyDd4F4qAQ"
r1 = urllib2.urlopen(website)
mydata = r1.read()
soup = BeautifulSoup(mydata)
s = soup.prettify()
x = soup.find_all("p", attrs={"class": "point-forecast-icons-low"})
y = soup.find_all("p", attrs={"class": "point-forecast-icons-high"})
print x
print y
它给了我这个:
[<p class="point-forecast-icons-low">Low: 40 °F</p>, <p class="point-forecast-icons-low">Low: 48 °F</p>, <p class="point-forecast-icons-low">Low: 26 °F</p>, <p class="point-forecast-icons-low">Low: 31 °F</p>, <p class="point-forecast-icons-low">Low: 32 °F</p>]
[<p class="point-forecast-icons-high">High: 67 °F</p>, <p class="point-forecast-icons-high">High: 53 °F</p>, <p class="point-forecast-icons-high">High: 44 °F</p>, <p class="point-forecast-icons-high">High: 47 °F</p>]
但是我只想说“高:##”和“低:##”的部分。
我怎么做??
您有元素列表。 在每个单独的元素上使用Element.text
属性:
lows = [low.text for low in soup.find_all("p", class_="point-forecast-icons-low")]
highs = [high.text for high in soup.find_all("p", class_="point-forecast-icons-high")]
这将产生:
>>> lows = [low.text for low in soup.find_all("p", class_="point-forecast-icons-low")]
>>> highs = [high.text for high in soup.find_all("p", class_="point-forecast-icons-high")]
>>> lows
[u'Low: 40 \xb0F', u'Low: 48 \xb0F', u'Low: 26 \xb0F', u'Low: 31 \xb0F', u'Low: 32 \xb0F']
>>> highs
[u'High: 67 \xb0F', u'High: 53 \xb0F', u'High: 44 \xb0F', u'High: 47 \xb0F']
所述°
在°F
不是ASCII打印字符所以它被表示为\\xb0
在一个列表中所示,当转义序列。 您可以打印单个值:
>>> print highs[0]
High: 67 °F
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.