java—通过xpath查找元素并将其存储为字符串

pvcm50d1  于 2021-06-30  发布在  Java
关注(0)|答案(0)|浏览(178)

我正在尝试通过xpath在网页上查找元素,并将其存储为字符串以供以后使用。我受够了。我认为我的代码做得不对。它打开url进行我需要的搜索,但没有存储任何元素,或者它就是找不到它
你能帮我一下吗?谢谢!
我的代码:

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.json.JSONObject;
import org.json.XML;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

import com.Uiproject.flickr.APIprop;

public class renaming {
    public static void main(String[] args) {
        WebDriver driver;
        String baseUrl;
        Client client;
        client = ClientBuilder.newClient();
        String FlickrUrl = APIprop.flickrurl;
        Invocation.Builder invocationBuilder = client.target(FlickrUrl)
                .request(MediaType.APPLICATION_JSON);
        Response response = invocationBuilder.get();
        String content = response.readEntity(String.class);
        System.out.println(content);
        JSONObject jsonresponse = XML.toJSONObject(content)
                .getJSONObject("rsp").getJSONObject("photos")
                .getJSONObject("photo");

        String title = jsonresponse.getString("title");

        driver = new FirefoxDriver();
        baseUrl = "http://www.airliners.net";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        driver.get(baseUrl + "/");
        driver.findElement(By.id("q")).click();
        driver.findElement(By.id("q")).clear();
        driver.findElement(By.id("q")).sendKeys(title);
        driver.findElement(By.name("submit")).click();

        new Select(driver.findElement(By.name("sort_order")))
                .selectByVisibleText("Latest Additions First");
        driver.findElement(By.cssSelector("option[value=\"photo_id desc\"]"))
                .click();
        List<WebElement> resultList = driver
                .findElements(By
                        .xpath(".//html/body/div/div[3]/div/table[2]/tbody/tr[2]/td[1]/div[1]/table/tbody/tr[1]/td/table/tbody/tr[2]/td[2]/table/tbody/tr/td/font/a[1]"));
        for (WebElement resultItem : resultList) {
            String tabname = resultItem.getText();
            System.out.println(tabname);
        }

        driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
        driver.quit();

    }
}

问题出在xpath中,正确的问题如下: //div[@id='content']/div/table[2]/tbody/tr[2]/td/div/table/tbody/tr/td/table/tbody/tr[2]/td[2] 谢谢大家!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题