尝试使用 R 从网页中抓取商业网站
Trying to scrape business website from webpage with R
我正在尝试抓取网站 link:
来自预约弹出窗口的联系人
https://www.theknot.com/marketplace/an-elegant-affair-cedar-falls-ia-537984 使用 R Studio。
我试过了
page <- read_html("https://www.theknot.com/marketplace/an-elegant-affair-cedar-falls-ia-537984")
Website <- html_attr(html_nodes(page,xpath = '//*[@id="appointment-vendors-categories"]/div/div[3]/div[1]/span/a'),"href")
这是我的输出:character(0)。
期望的输出是:https://www.anelegantaffairbridal.com/?utm_source=theknot.com&utm_medium=referral&utm_campaign=theknot
我使用下面的代码成功地从页面底部的联系人部分抓取了信息,但同样的方法似乎不适用于 link。
Name_of_Vendor2 <- substr((page %>% html_nodes("h3") %>% html_text),18,70)
Phone_of_Vendor <- html_text(html_nodes(page, xpath = "//div[@class = 'contact-info--900c8 body1--711dc']/span[2]"))
Address_of_Vendor <- html_text(html_nodes(page, xpath = "//div[@class = 'contact-info--900c8 body1--711dc']/span[1]"))
查看下载的 html 后,使用 rvest::write_xml(page, file="temp.html")
将其写入文件。然后我继续搜索 URL 并在最后一个 script
标签中找到它作为 JSON
对象,url 的键是 websiteUrl
.所以我选择了最后一个脚本标签和 运行 其内容上的正则表达式以获取 URL
scripts <- html_nodes(page,xpath = '//script[@type="text/javascript"]')
script <- html_text(scripts[[length(scripts)-1]])
stringr::str_extract(script,'(?<="websiteUrl":").+?(?=")')
#> [1] "http://www.AnElegantAffairBridal.com?utm_source=theknot.com&utm_medium=referral&utm_campaign=theknot"
我正在尝试抓取网站 link:
来自预约弹出窗口的联系人 https://www.theknot.com/marketplace/an-elegant-affair-cedar-falls-ia-537984 使用 R Studio。
我试过了
page <- read_html("https://www.theknot.com/marketplace/an-elegant-affair-cedar-falls-ia-537984")
Website <- html_attr(html_nodes(page,xpath = '//*[@id="appointment-vendors-categories"]/div/div[3]/div[1]/span/a'),"href")
这是我的输出:character(0)。 期望的输出是:https://www.anelegantaffairbridal.com/?utm_source=theknot.com&utm_medium=referral&utm_campaign=theknot
我使用下面的代码成功地从页面底部的联系人部分抓取了信息,但同样的方法似乎不适用于 link。
Name_of_Vendor2 <- substr((page %>% html_nodes("h3") %>% html_text),18,70)
Phone_of_Vendor <- html_text(html_nodes(page, xpath = "//div[@class = 'contact-info--900c8 body1--711dc']/span[2]"))
Address_of_Vendor <- html_text(html_nodes(page, xpath = "//div[@class = 'contact-info--900c8 body1--711dc']/span[1]"))
查看下载的 html 后,使用 rvest::write_xml(page, file="temp.html")
将其写入文件。然后我继续搜索 URL 并在最后一个 script
标签中找到它作为 JSON
对象,url 的键是 websiteUrl
.所以我选择了最后一个脚本标签和 运行 其内容上的正则表达式以获取 URL
scripts <- html_nodes(page,xpath = '//script[@type="text/javascript"]')
script <- html_text(scripts[[length(scripts)-1]])
stringr::str_extract(script,'(?<="websiteUrl":").+?(?=")')
#> [1] "http://www.AnElegantAffairBridal.com?utm_source=theknot.com&utm_medium=referral&utm_campaign=theknot"