gpt4 book ai didi

r - 网络抓取 : replacing tags manually

转载 作者:行者123 更新时间:2023-12-04 16:10:54 25 4
gpt4 key购买 nike

我正在处理和玩“rvest”。使用“read_html”获取数据是可以的。

library(rvest)
# suppressMessages(library(dplyr))
library(stringr)
library(XML)

# get house data
houseurl <- "http://boekhoff.de/immobilien/gepflegtes-zweifamilienhaus-in-ellwuerden/"
house <- read_html(houseurl)
house

我在处理数据时遇到了一些问题。我的问题在源代码中进行了评论。

## eleminating <br>-tags in address
# using the following commands causes error using "html_nodes"
str_extract_all(house,"<br>") ## show all linebreaks
# replacing <br> in whitespace " ",
house <- str_replace_all(house,"<br>", " ")

现在正在读出详细信息,但似乎不起作用

houseattribut <- house %>%
html_nodes(css = "div.col-2 li p.data-left") %>%
html_text(trim=TRUE)
# shows "Error in UseMethod("xml_find_all") : ... "
# but all attributes are shown on screen
houseattribut

无需手动替换“br”标签即可正常工作,但“html_text”将字符串收紧了

housedetails <- house %>%
html_nodes(css = "div.col-2 li p.data-right") %>%
html_text()
housedetails
# the same error shows "Error in UseMethod("xml_find_all") : ... "
# but all details are shown on screen

housedetails[4]
# in the source there is: "Ellwürder Straße 17<br>26954 Nordenham"
# at <br>-tag should be a whitespace

任何提示我做错了什么?

最佳答案

问题是当你使用read_html时,house是一个xml_document,在你使用str_replace_all之后它变成了 chr,因此,当您再次尝试过滤节点时,它不再是 xml_document,它会给出错误。

您需要将其再次转换为 xml_document 或逐个节点应用替换。

类似的东西:

house <- read_html(str_replace_all(house,"<br>", " "))

完整代码:

library(rvest)
#> Loading required package: xml2
library(stringr)

houseurl <- "http://boekhoff.de/immobilien/gepflegtes-zweifamilienhaus-in-ellwuerden/"
house <- read_html(houseurl)

house <- read_html(str_replace_all(house,"<br>", " "))

housedetails <- house %>%
html_nodes(css = "div.col-2 li p.data-right") %>%
html_text()

housedetails[4]
#> [1] "Ellwürder Straße 17 26954 Nordenham"

关于r - 网络抓取 : replacing tags manually,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41812820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com