我在找到正确的标签以从网页中抓取我想要的文本时遇到了一些麻烦。 HTML 示例如下。我想抓取文本“墨尔本风暴已经实现了 4 次尝试布里斯班野马队已经实现了 2 次尝试”
我一直在使用的 R 代码如下,我似乎无法得到我想要的文本。
url <- 'https://www.nrl.com/draw/nrl-premiership/2019/round-1/storm-v-broncos/'
RawTable <- read_html(url)
RawTable <- html_nodes(RawTable,'.u-visually-hidden')
RawTable <- html_text(RawTable)
RawTable <- data.frame(RawTable)
HTML 代码:
`<div class="Match-centre-summary o-shadowed-box u-spacing-mb-small">
<span class="u-visually-hidden">Melbourne Storm has achieved 4 Tries Brisbane Broncos has achieved 2
Tries </span>`
答案 0 :(得分:0)
我认为您正在下载的页面没有该文本。
我认为正在进行某种重定向。
如果你这样做:
def get_temperature():
while True:
celsius = input("Degree in Celsius ")
try:
celsius = float(celsius)
return celsius
except ValueError:
print("Try numbers.")
def is_it_to_cold(celsius):
while True:
if celsius >= -273.15:
return celsius
else:
print("not below -273.15 ")
celsius = get_temperature()
print(celsius)
return celsius
def convert_to_kalvin(celsius):
kalvin = celsius + 273.15
return kalvin
if __name__ == "__main__":
celsius = get_temperature()
print(celsius)
#This below should fix your error
celsius = is_it_to_cold(celsius)
print(str(convert_to_kalvin(celsius)) + "+Degree Kalvin.")
然后在浏览器中打开 temp.html 是你想要的源代码吗?
答案 1 :(得分:0)
像这样的网页需要一些典型的特殊技巧,例如 Rselenium。查看此网页,您请求的数据似乎以 JSON 数据的形式存储在属性中,然后由浏览器呈现。
在这种情况下,可以使用 rvest 检索属性数据,然后将 JSON 数据转换为列表和/或数据帧。
library(rvest)
library(dplyr)
library(jsonlite)
url <- 'https://www.nrl.com/draw/nrl-premiership/2019/round-1/storm-v-broncos/'
page <- read_html(url)
contentnodes <-page %>% html_nodes ("div.l-content.pre-quench") %>%
html_attr("q-data") %>% jsonlite::fromJSON()
发生的事情是我们正在寻找具有“class= l-content pre-quench”的 div 节点。在该节点中有一个名为“q-data”的属性。我们要检索的是该属性的数据。 fromJSON()
正在将属性的 JSON 数据转换为一个包含许多嵌套列表和数据框的列表,其中包含与匹配相关的所有信息。
您需要计算出所需信息的结构。